Last active
August 5, 2017 01:17
-
-
Save cixuuz/536af62b875faa80e11c11c9e42e4af9 to your computer and use it in GitHub Desktop.
[235 Lowest Common Ancestor of a Binary Search Tree] #leetcode
This file contains hidden or 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
/** | |
* Definition for a binary tree node. | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode(int x) { val = x; } | |
* } | |
*/ | |
public class Solution { | |
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { | |
if ((root.val - p.val) * (root.val - q.val) < 1) { | |
return root; | |
} | |
if (root.val > p.val) { | |
return lowestCommonAncestor(root.left, p, q); | |
} else { | |
return lowestCommonAncestor(root.right, p, q); | |
} | |
} | |
} | |
public class Solution2 { | |
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { | |
while ((root.val - p.val) * (root.val - q.val) >= 1) { | |
root = root.val > p.val? root.left : root.right; | |
} | |
return root; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment