Lowest Common Ancestor of a Binary Search Tree
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5思路
// java
public class Solution {
TreeNode ret = null;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) return null;
if (root.val < p.val && root.val < q.val)
return lowestCommonAncestor(root.right, p, q);
if (root.val > p.val && root.val > q.val)
return lowestCommonAncestor(root.left, p, q);
else
return root;
}
}Iterative Java Solution
Last updated