链接:http://www.lintcode.com/zh-cn/problem/lowest-common-ancestor/
给定一棵二叉树,找到两个节点的最近公共父节点(LCA)。
最近公共祖先是两个节点的公共的祖先节点且具有最大深度。
注意事项
假设给出的两个节点都在树中存在
样例
对于下面这棵二叉树
4
/ \
3 7
/ \
5 6
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
class Solution {
public:
/*
* @param root: The root of the binary search tree.
* @param A: A TreeNode in a Binary.
* @param B: A TreeNode in a Binary.
* @return: Return the least common ancestor(LCA) of the two nodes.
*/
TreeNode * lowestCommonAncestor(TreeNode * root, TreeNode * A, TreeNode * B) {
// write your code here
if(!root)
return NULL;
if(root==A)
return A;
if(root==B)
return B;
TreeNode *L=lowestCommonAncestor(root->left,A,B);
TreeNode *R=lowestCommonAncestor(root->right,A,B);
if(L&&R) //如果A和B都在root的子节点中,返回root
return root;
return L?L:R;
}
};