Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Last active August 5, 2017 01:17
Show Gist options
  • Save cixuuz/536af62b875faa80e11c11c9e42e4af9 to your computer and use it in GitHub Desktop.
Save cixuuz/536af62b875faa80e11c11c9e42e4af9 to your computer and use it in GitHub Desktop.
[235 Lowest Common Ancestor of a Binary Search Tree] #leetcode
/**
* 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