Created
March 15, 2013 00:09
-
-
Save Ray1988/5166439 to your computer and use it in GitHub Desktop.
common ancester of two treeNodes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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