235 Lowest Common Ancestor of a Binary Search Tree
235. Lowest Common Ancestor of a Binary Search Tree
1. Question
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 52. Implementation
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root.val < Math.min(p.val, q.val)) {
return lowestCommonAncestor(root.right, p, q);
}
else if (root.val > Math.max(p.val, q.val)) {
return lowestCommonAncestor(root.left, p, q);
}
else {
return root;
}
}
}3. Time & Space Complexity
Last updated