- "A node is a descendant of itself"
- "All node values are unique"
- "
p
andq
are different and both values will exist in the BST"
Notice this is not a binary search tree. If it was, it would be equivalent to this problem, which is simpler to solve.
- Search left subtree. If we find
p
orq
, return that node. - Search right subtree. If we find
p
orq
, return that node. - If
left
is null,p
andq
must be in the right subtree - If
right
is null,p
andq
must be in the left subtree - If neither are null,
p
is on one side,q
is on other side, so the current node is the lowest common ancestor.
class TreeNode {
TreeNode left;
TreeNode right;
}
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
return dfs(root, p, q);
}
public TreeNode dfs(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
} else if (root == p || root == q) {
return root;
}
TreeNode left = dfs(root.left, p, q);
TreeNode right = dfs(root.right, p, q);
if (left == null) {
return right;
} else if (right == null) {
return left;
} else {
return root;
}
}
}
- Time Complexity: O(n) since we may have to search all the nodes.
- Space Complexity: O(log n) if balanced tree, O(n) otherwise. The space complexity is due to recursion.