Skip to content

Instantly share code, notes, and snippets.

@Ray1988
Created March 15, 2013 00:09
Show Gist options
  • Save Ray1988/5166439 to your computer and use it in GitHub Desktop.
Save Ray1988/5166439 to your computer and use it in GitHub Desktop.
common ancester of two treeNodes
public TreeNode findCommonAnces(TreeNode r, TreeNode a, TreeNode b){
if(r==null) return null;
if(r==a||r==b) return r;
boolean leftCover_a=cover(r.left, a);
boolean leftCover_b=cover(r.left, b);
if(leftCover_a!=leftCover_b) return r;
TreeNode child=leftCover_a?r.left:r.right
TreeNode common=findCommonAnces(child, a, b);
return common
}
public boolean cover(TreeNode root, TreeNode a){
if(root==null&&a!=null) return false;
if(a==null) return true;
if(root==a) return true;
return cover(root.left, a)||cover(root.right, a);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment