# 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;
}

#### 1143. Lowest Common Ancestor (30)

2018-03-18 22:15:07

#### [PAT] c++ 1143. Lowest Common Ancestor (30)

2018-03-18 22:03:07

#### leetcode 235: Lowest Common Ancestor of a Binary Search Tree

2015-07-11 06:34:08

#### 【LeetCode】 Lowest Common Ancestor 最近公共祖先 - Medium

2017-10-18 00:18:00

#### Lowest Common Ancestor II

2017-09-04 21:33:04

#### 最近公共祖先 (Lowest common ancestor)

2012-06-05 11:07:59

#### 235. Lowest Common Ancestor of a Binary Search Tree [easy] (Python)

2016-05-25 15:26:02

#### Lowest Common Ancestor问题的解决思路

2013-08-19 18:51:38

#### [LeetCode 236] Lowest Common Ancestor of a Binary Tree

2015-08-25 13:31:55

#### leetcode 236: Lowest Common Ancestor of a Binary Tree

2015-07-14 02:35:39