Given a binary tree, find the lowest common ancestor (LCA) of two given nodes
in the tree.
_______3______ / \ ___5__ ___1__ / \ / \ 6 _2 0 8 / \ 7 4For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another
example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself
according to the LCA definition.
也可以用递归来实现。
在root为根的二叉树中找A,B的LCA:
如果找到了就返回这个LCA
如果只碰到A,就返回A
如果只碰到B,就返回B
如果都没有,就返回null
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null||root==p||root==q)
return root;
TreeNode left=lowestCommonAncestor(root.left, p, q);
TreeNode right=lowestCommonAncestor(root.right, p, q);
if(left!=null&&right!=null)
return root;
if(left!=null)
return left;
if(right!=null)
return right;
return null;
}