Created
July 20, 2014 19:07
-
-
Save iwilbert/66236a13a579b9c117d4 to your computer and use it in GitHub Desktop.
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 LCA(TreeNode root, TreeNode p, TreeNode q) { | |
if (root == null) | |
return null; | |
if (!isExisted(root, p) || !isExisted(root, q)) | |
return null; | |
return LCA_helper(root, p, q); | |
} | |
private boolean isExisted(TreeNode root, TreeNode node) { | |
if (root == null) | |
return false; | |
if (root == node) | |
return true; | |
return isExisted(root, node.left) || isExisted(root, node.right); | |
} | |
private TreeNode LCA_helper(TreeNode root, TreeNode p, TreeNode q) { | |
if (root == null) | |
return null; | |
if (root == p || root == q) | |
return root; | |
// only look at left side | |
boolean ponleft = isExisted(root.left, p); | |
boolean qonleft = isExisted(root.left, q); | |
if (ponleft != qonleft) | |
return root; | |
else if (ponleft) | |
return LCA_helper(root.left, p, q); | |
else | |
return LCA_helper(root.right, p, q); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment