Question:
Find out the Lowest Common Ancestor of two nodes in a Binary Tree.
分析:
LCA的问题,在leetcode的主页上有详解,包括二叉树、二叉搜索树。
如果是二叉搜索树,遍历树节点,如果两个给定节点大于/小于树节点,那么遍历位置右移/左移,直到给定节点等于树节点或者分别在当前树节点的左右两侧,返回当前树节点。复杂度O(log(n))。
如果是二叉树,递归法,从根节点起,寻找左右子树是否存在给定节点,如果返回的左子树右子树都不为空,那么当前的节点就是结果;如果左右有一个为空,那么返回的不为空的子树节点为结果。Base Case是,当前节点为空,返回空;当前节点等于给定节点其中一个,返回当前节点。
代码:
//binary Tree
public Node LCA(Node root, Node x1, Node x2){
if(root == null) return null;
if(root==x1 || root==x2) return root;
Node l = LCA(root.left, x1, x2);
Node r = LCA(root.right, x1, x2);
if(l!=null && r!=null) return root;
return l!=null?l:r;
}
//BST
public Node getAnces(Node root, Node x1, Node x2){
if(root==null || x1==null || x2==null) return null;
if(root.compareTo(x1)>0 && root.compareTo(x2)>0) return getAnces(root.left, x1, x2);
else if(root.compareTo(x1)<0 && root.compareTo(x2)<0) return getAnces(root.right, x1, x2);
else return root;
}
总结:
经典题目。