struct TreeNode{

int val;

TreeNode* left;

TreeNode* right;

TreeNode(int val):val(val),left(NULL),right(NULL){}

};

Not all binary trees are binary search trees.

4.1 Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one.

Calculate all node's two leaf by recursion, in each recursion, judge its two leaf nodes differ is more than one or not. -1 represents no balanced, and >=0 represents balanced.

int depthAndCheck(TreeNode *root){

if(root==NULL)return 0;

else{

int leftD = depthAndCheck(root->left);

int rightD = depthAndCheck(root->right);

if(leftD==-1||rightD==-1)return -1; //find one node no balanced,then the tree is no balanced.

if(leftD-rightD<=-2||leftD-rightD>=2)return -1; //judge its two children.

return max(leftD,rightD)+1;

}

}

4.2 Given a directed graph, design an algorithm to find out whether there is a route between two nodes.

struct GraphNode{

int val; //value

vector<GraphNode*> next; //directed to nodes

};

Here, two nodes are A and B, we breadth first search the graph at the beginning of A to see whether there is a route from A to B, then breadth first search at the beginning of B to see whether there is a route from B to
A. We declare a set<GraphNode*> to record whether the Node is visited.

bool isHaveRoute(GraphNode *A,GraphNode *B){

if(A==B)return true;

set<GraphNode*>  visited;

list<GraphNode*>  array[2];

int cur=0,pre=1;

array[0].push(A);visited.insert(A);

while(!array[cur].empty()){

cur=!cur;pre=!pre;

array[cur].clear();

while(!array[pre].empty()){

for(int i=0;i<array[pre].front()->next.size();i++){

if(visited.count(array[pre].front()->next[i])==0){

if(array[pre].front()->next[i]==B)return true;

array[cur].push(array[pre].front()->next[i]);

visited.insert(array[pre].front()->next[i]);

}

}

array[pre].pop_front();

}

}

return false;

}

bool isHaveRouteAB(GraphNode *A,GraphNode *B){

if(isHaveRoute(A,B)||isHaveRoute(B,A))return true;

else return false;

}

4.3 Given a sorted (increasing order) array, write an algorithm to create a binary tree with minimal height.

I think the problem is to create a binary search tree with minimal height.

The left child is smaller than the parent and the right child is bigger than the parent. So, we can find the middle of the array, and divide this array to two part, the left part is the left child part of the middle and
the right part is the right child part.

TreeNode* binaryST(int a[],int left,int right){

if(left>right)return NULL;

int mid=left+(right-left)/2;

TreeNode *parent = new TreeNode(a[mid]);

parent->left = binaryST(a,left,mid-1);

parent->right = binaryST(a,mid+1,right);

return parent;

}

TreeNode *resBST(int a[],int n){

if(n<=0)return NULL;

return binaryST(a,0,n-1);

}

4.4 Given a binary search tree, design an algorithm which creates a linked list of all the nodes at each depth (i e , if you have a tree with depth D, you’ll have D linked lists).

BFS,like 4.2.

4.5 Write an algorithm to find the ‘next’ node (i e , in-order successor) of a given node in a binary search tree where each node has a link to its parent.

in-order, first, read the node's left, then the node, the the node's right.

When the node has right child, the successor will be the left-most child of it's right child part.

When the node is a left child,its parent is its successor.

When the node is a right child, traverse its parents until we find a parent that the node is in the left child part of this parent. This parent is the node's successor.

TreeNode* findNextNode(TreeNode* root){

if(root!=NULL)

if(root->parent==NULL||root->right!=NULL){

return findLeftMostChild(root->right);

}else{

while(root->parent){

if(root->parent->left==root)break;

root=root->parent;

}

return root->parent;

}

}

return NULL;

}

TreeNode* findLeftMostChild(TreeNode* root){

if(root==NULL)return NULL;

if(root->left)root=root->left;

return root;

}

4.6 Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree.Avoid storing additional nodes in a data structure NOTE: This is not necessarily a binary search tree.

4.7 You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes Create an algorithm to decide if T2 is a subtree of T1.

we traverse T1 to find a node that equal to T2's root, then compare T1 and T2 to find whether T2 is a subtree of T1.

bool isSubTree(TreeNode* T1,TreeNode* T2){

if(T2==NULL)return true;

if(T1==NULL)return false;

if(T1->val==T2->val){

if(isMatch(T1,T2))return true;

}

return isSubTree(T1->left,T2)||isSubTree(T1->right,T2);

}

bool isMatch(TreeNode* T1,TreeNode *T2){

if(T1==NULL&&T2==NULL)return true;

if(T1==NULL||T2==NULL)return false;

if(T1->val!=T2->val)return false;

return isMatch(T1->left,T2->left)&&isMatch(T1->right,T2->right);

}

4.8 You are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum up to that value. Note that it can be any path in the tree - it does not have to start at the root.

we declare a vector<int> to store one path from root to current node, and traverse this vector to find a path that sum up to the value.

void traverseAllPaths(TreeNode* root,int num,vector<int> buffer,int level){

if(root==NULL)return;

buffer.push_back(root->val);

int temp=num;

for(int i=level;i>=0;i--){

temp-=buffer[i];

if(temp==0)printfPath(buffer,i,level);

}

vector<int> bufferL,bufferR;

for(int i=0;i<buffer.size();i++){

bufferL.push_back(buffer[i]);

bufferR.push_back(buffer[i]);

}

traverseAllPaths(root->left,num,bufferL,level+1);

traverseAllPaths(root->right,num,bufferR,level+1);

}

void printfPath(vector<int> buffer,int begin,int end){

for(int i=begin;i<=end;i++)printf("%d ",buffer[i]);

printf("\n");

}

CareerCup Chapter 4 Trees and Graphs的更多相关文章

  1. Cracking the Coding Interview(Trees and Graphs)

    Cracking the Coding Interview(Trees and Graphs) 树和图的训练平时相对很少,还是要加强训练一些树和图的基础算法.自己对树节点的设计应该不是很合理,多多少少 ...

  2. 【CareerCup】Trees and Graphs—Q4.3

    转载请注明出处:http://blog.csdn.net/ns_code/article/details/24744177     题目: Given a sorted (increasing ord ...

  3. Chp4: Trees and Graphs

    1.Type of Tree 1. Binary Tree: a binary tree is a tree in which each node has at most two child node ...

  4. Careercup | Chapter 1

    1.1 Implement an algorithm to determine if a string has all unique characters. What if you cannot us ...

  5. Careercup | Chapter 4

    二叉查换树,左孩子小于等于根,右孩子大于根. 完全二叉树,除最后一层外,每一层上的节点数均达到最大值:在最后一层上只缺少右边的若干结点. complete binary tree 满二叉树,完美二叉树 ...

  6. Careercup | Chapter 3

    3.1 Describe how you could use a single array to implement three stacks. Flexible Divisions的方案,当某个栈满 ...

  7. Careercup | Chapter 2

    链表的题里面,快慢指针.双指针用得很多. 2.1 Write code to remove duplicates from an unsorted linked list.FOLLOW UPHow w ...

  8. Careercup | Chapter 8

    8.2 Imagine you have a call center with three levels of employees: respondent, manager, and director ...

  9. Careercup | Chapter 7

    7.4 Write methods to implement the multiply, subtract, and divide operations for integers. Use only ...

随机推荐

  1. Java Swing界面编程(31)---菜单条:JMenu

    package com.beyole.test; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMe ...

  2. POJ题目分类【实在是不知道哪个是原创了】

    原地址:http://blog.csdn.net/liuqiyao_01/article/details/8477801 初期:一.基本算法:     (1)枚举. (poj1753,poj2965) ...

  3. mysql 服务启动报1607 error

    [问题说明] mysql曾经还是好好的,突然就不行了...不知道是否使用了腾讯C盘搬家工具引起的... watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc2h ...

  4. Hadoop-2.2.0中国文献—— MapReduce 下一代 -- 公平调度

    目的 此文档描写叙述了 FairScheduler, Hadoop 的一个可插入式的调度器.同意 YARN 应用在一个大集群中公平地共享资源. 简单介绍 公平调度是一种分配资源给应用的方法,以致到最后 ...

  5. Web Api 2(Cors)Ajax跨域访问

    支持Ajax跨域访问ASP.NET Web Api 2(Cors)的简单示例教程演示   随着深入使用ASP.NET Web Api,我们可能会在项目中考虑将前端的业务分得更细.比如前端项目使用Ang ...

  6. SE 2014年4月8日

    1.路由引入的作用? 当网络中运行多种路由协议的时候,由于不同协议的路由算法和度量值等均不相同,路由引入可以将不同协议的路由引入到当前的路由协议中,保证网络的互通. 对比单向入和双向入 单向引入是只将 ...

  7. HGE基础教程

    作者:寰子 来源:http://www.hgechina.com/前言: 写道: 无意中发现了hge中文社区,听朋友介绍,认识了hge,然后开始对它进行研究,并使用hge开始制作游戏. 因为我所得的资 ...

  8. [WPF] 使用Grid与GridSplitter排版布局

    原文:[WPF] 使用Grid与GridSplitter排版布局 前言 在開發應用程式時,一個很重要的工作項目就是設計使用者介面的排版布局.WPF中所提供的Grid控制項,讓開發人員擁有將版面分割為欄 ...

  9. U10vim程序编辑器

    vim需要多加练习. 1.你可以将vim视为vi的高级版本.vi分成三种模式:一般模式,编辑模式和命令行模式. 一般模式:以vi打开一个文件就直接进入一般模式了(这也是默认的模式).在这个模式中,你可 ...

  10. 怎样让你的安卓手机瞬间变Firefox os 畅玩firefox os 应用

    Firefox os 手机迟迟不能在国内大面积上市.如今能买到的Firefox os手机国内就一款Firefox os ZET OPEN C ,但这款手机配置确实还不如人意.价格方面也不实惠,对于我们 ...