# LeetCode_Lowest Common Ancestor

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

LeetCode上有人给出了Lowest Common Ancestor of a Binary Tree Part I一个自底向上的解法。

A Bottom-up Approach (Worst case O(n) ):
Using a bottom-up approach, we can improve over the top-down approach by avoiding traversing the same nodes over and over again.

We traverse from the bottom, and once we reach a node which matches one of the two nodes, we pass it up to its parent. The parent would then test its left and right subtree if each contain one of the two nodes. If yes, then the parent must be the LCA and we pass its parent up to the root. If not, we pass the lower node which contains either one of the two nodes (if the left or right subtree contains either p or q), or NULL (if both the left and right subtree does not contain either p or q) up.

class Solution{
public:
TreeNode *LowestCommonAncestor(TreeNode *root,TreeNode *n1,TreeNode *n2){
//如果当前根结点为空返回NULL
if (root==NULL){
return NULL;
}
//若当前找到n1或者n2其中一个，则直接返回
if(root==n1||root==n2){
return root;
}
//分别从左右子树中查找n1和n2
TreeNode *left=LowestCommonAncestor(root->left,n1,n2);
TreeNode *right=LowestCommonAncestor(root->right,n1,n2);
//若正好在分别在左右子树中找到n1和n2则说明当前节点就是要找的解
if (left&&right){
return root;
}
//存在三种情况是的函数在此处返回
//1.第一次在左或右子树中找到n1、n2中的某个节点
//2.从在当前节点的左右子树中已经查找到要找的解
//3.以当前节点为根的子树根本就不存在n1和n2
return left?left:right;
}
};

void preOrderPrintTree(TreeNode * root){
if (root==NULL)  {
cout<<"#"<<" ";
return;
}
cout<<root->val<<" ";
preOrderPrintTree(root->left);
preOrderPrintTree(root->right);
}

void FindNode(TreeNode *root ,int val ,TreeNode *&pf){
if (root==NULL){
return;
}
if (root->val==val){
pf=root;
return;
}
FindNode(root->left,val,pf);
FindNode(root->right,val,pf);
}
int _tmain(int argc, _TCHAR* argv[])
{
string str="{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}";
TreeNode *root=StringToBinaryTree(str);
cout<<"PreOrder Travellsor:"<<endl;
preOrderPrintTree(root);
cout<<endl;
TreeNode *n1=NULL;
FindNode(root,16,n1);
TreeNode *n2=NULL;
FindNode(root,8,n2);
Solution ss;
TreeNode *CommonAncester = ss.LowestCommonAncestor(root,n1,n2);
cout<<"8 and 11 Lowest common Ancestor:"<<CommonAncester->val<<endl;
return 0;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120