Lowest Common Ancestor of a Binary Tree
Scratchpad
Saved in this browser
Problem
Section titled “Problem”Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
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).”
Example 1:
![Binary tree [3,5,1,6,2,0,8,null,null,7,4]](https://assets.leetcode.com/uploads/2018/12/14/binarytree.png)
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1Output: 3Explanation: The LCA of nodes 5 and 1 is 3.Example 2:
![Binary tree [3,5,1,6,2,0,8,null,null,7,4]](https://assets.leetcode.com/uploads/2018/12/14/binarytree.png)
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4Output: 5Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.Example 3:
Input: root = [1,2], p = 1, q = 2Output: 1Constraints:
- The number of nodes in the tree is in the range .
-
Node.val - All
Node.valare unique. p != qpandqwill exist in the tree.
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”Unlike a BST, the values tell us nothing about where p and q are, so we have to search. Let the recursive call on a subtree return:
porqif that node is found in the subtree (whichever is met first going down),- the LCA if both are in the subtree,
nullptrif neither is.
Combine the answers bottom-up (post-order). At a node root:
- If
rootisporq, return it. If the other target is below it,rootis still the LCA (a node is a descendant of itself), and if the other target is elsewhere, an ancestor will notice. - If the left subtree and the right subtree both return non-null,
pis on one side andqon the other.rootis the lowest node joining them — the LCA. - If only one side returns non-null, pass that result up: it is either one target (the other is not below
root) or an LCA already found deeper.
Algorithm
Section titled “Algorithm”- If
rootisnullptr,porq, returnroot. left = lowestCommonAncestor(root->left, p, q),right = lowestCommonAncestor(root->right, p, q).- If both are non-null, return
root; otherwise return whichever is non-null (ornullptr).
Walkthrough
Section titled “Walkthrough”Example 1 (p = 5, q = 1). Each edge is labelled with what the child returns to its parent:
The calls on 5 and 1 return immediately because those nodes are targets (grey subtrees are never explored). At 3 both sides are non-null, so 3 is the LCA. In Example 2 (q = 4 inside the subtree of 5), the call on 5 again returns 5 straight away and the right side returns nullptr, so 5 is passed up as the answer.
Complexity
Section titled “Complexity”- Time: — each node is visited at most once.
- Space: — the recursion stack, where
his the height of the tree ( for a skewed tree).
Edge cases
Section titled “Edge cases”- One target is an ancestor of the other (Examples 2 and 3): the search stops at the upper target and returns it, which is the correct LCA.
- Targets are compared by pointer, not value, so the code relies only on
pandqbeing nodes of this tree.
Think before you peek
Work out an approach on your own first — the explanation will still be here when you want it.
class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (!root || root == p || root == q) return root; TreeNode* left = lowestCommonAncestor(root->left, p, q); TreeNode* right = lowestCommonAncestor(root->right, p, q); if (left && right) return root; // p and q are on different sides return left ? left : right; }};class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null || root == p || root == q) return root; TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if (left != null && right != null) return root; // p and q are on different sides return left != null ? left : right; }}class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': # The same post-order recursion, run on an explicit stack (the tree can be 10^5 levels deep). found = {} # node -> what the recursive call on it returns (None when neither target is below) stack = [(root, False)] while stack: node, children_done = stack.pop() if node is p or node is q: found[node] = node elif children_done: left = found.pop(node.left, None) right = found.pop(node.right, None) found[node] = node if left and right else left or right # both sides -> node is the LCA else: stack.append((node, True)) for child in (node.left, node.right): if child: stack.append((child, False)) return found[root]Give it a try first
Attempt the problem on LeetCode — the code will still be here.
