Design an algorithm and write code to find the first common ancestor of two nodes
in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not
necessarily a binary search tree.
解法1: recursively
public boolean isCover(TreeNode node, TreeNode t){
if(node==t) return true;if(node==null) return false;
return isCover(node.left,t)|| isCover(node.right, t);
}
public TreeNode helper(TreeNode root, TreeNode p, TreeNode q){
if(root==null) return null;
if(root==p||root==q) return root; //important
boolean is_left_p = isCover(root.left, p);
boolean is_left_q = isCover(root.left, q);
if(is_left_q!=is_left_p) return root;
TreeNode child_side = is_left_p? node.left;node.right;
return helper(child_side, p, q);
}
public Node main(Node root, Node p, Node q){
if(!isCover(root,p))||!isCover(root,q)) return null;
return helper(root, p, q);
}
书中分析:This algorithm runsinO(n) time on a balanced tree.This is because covers is called on
2n nodes in the first call (n nodes for the left side, and n nodes for the right side). After
that, the algorithm branches left or right, at which point covers will be called on 2n/2
nodes, then 2n/4, and so on.This results in a runtime of 0(n).
解法2 冒泡