2013年8月7日
摘要: 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. 1 bool covers(Node *root,Node *p) 2 { 3 if(!root) return false; 4 if(root==p) return tru... 阅读全文
posted @ 2013-08-07 16:52 xuanxu 阅读(173) 评论(0) 推荐(0) 编辑
摘要: 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. 1 typedef struct Node 2 { 3 int val; 4 Node *left,*right,*parent; 5 }Node; 6 7 Node* GetSuccessor(Node* node) 8 { 9 if(node->right)10 ... 阅读全文
posted @ 2013-08-07 16:09 xuanxu 阅读(146) 评论(0) 推荐(0) 编辑
摘要: 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).#include typedef struct Node{ int val; Node *left,*right;}vector> findLevelList(Node *root){ int level = 0; vecto... 阅读全文
posted @ 2013-08-07 15:38 xuanxu 阅读(169) 评论(0) 推荐(0) 编辑
摘要: Given a sorted (increasing order) array, write an algorithm to create a binary tree with minimal height.typedef struct Node{ int val; Node *left,*right; Node(int v){ val = v;left = right = NULL;}}Node;Node* createTree(int a[],int start,int end){ if(startleft = createTree(a,start,mid-1); ... 阅读全文
posted @ 2013-08-07 15:17 xuanxu 阅读(150) 评论(0) 推荐(0) 编辑
摘要: Given a directed graph, design an algorithm to find out whether there is a route between two nodes.//BFS#include #include using namespace std;int n;bool visited[n];bool m[n][n];bool hasRoot(int src,int dst){ queue q; memset(visited,false,sizeof(visited)); q.push(src); while(!q.empty(... 阅读全文
posted @ 2013-08-07 14:41 xuanxu 阅读(207) 评论(0) 推荐(0) 编辑
摘要: 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. 1 int d=0,min=INT_MAX,max = INT_MIN; 2 3 void GetMaxAndMin(Node *root) 4 { 5 if(!root->l.. 阅读全文
posted @ 2013-08-07 13:21 xuanxu 阅读(132) 评论(0) 推荐(0) 编辑