Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5]
Example 1:
1
Input:
2
root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
3
4
Output:
5
6
6
7
Explanation:
8
The LCA of nodes 2 and 8 is 6.
Copied!
Example 2:
1
Input:
2
root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
3
4
Output:
5
2
6
7
Explanation:
8
The LCA of nodes 2 and 4 is 2
9
, since a node can be a descendant of itself according to the LCA definition.
Copied!
Note:
  • All of the nodes' values will be unique.
  • p and q are different and both values will exist in the BST.

Solution & Analysis

Using attribution of a BST

1
/**
2
* Definition for a binary tree node.
3
* public class TreeNode {
4
* int val;
5
* TreeNode left;
6
* TreeNode right;
7
* TreeNode(int x) { val = x; }
8
* }
9
*/
10
class Solution {
11
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
12
13
// Value of current node or parent node.
14
int parentVal = root.val;
15
16
// Value of p
17
int pVal = p.val;
18
19
// Value of q;
20
int qVal = q.val;
21
22
if (pVal > parentVal && qVal > parentVal) {
23
// If both p and q are greater than parent
24
return lowestCommonAncestor(root.right, p, q);
25
} else if (pVal < parentVal && qVal < parentVal) {
26
// If both p and q are lesser than parent
27
return lowestCommonAncestor(root.left, p, q);
28
} else {
29
// We have found the split point, i.e. the LCA node.
30
return root;
31
}
32
}
33
}
Copied!
Iterative
1
Copied!

Same code as Lowest Common Ancestor of a Binary Tree

1
public class Solution {
2
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
3
if(root == null || root == p || root == q) return root;
4
TreeNode left = lowestCommonAncestor(root.left, p, q);
5
TreeNode right = lowestCommonAncestor(root.right, p, q);
6
if(left != null && right != null) return root;
7
return left != null ? left : right;
8
}
9
}
Copied!

Reference

Last modified 1yr ago