Lowest Common Ancestor of a Binary Tree

Post-order DFS — return the first node whose left and right subtrees each contain one of p, q.

Medium
Time O(n) Space O(h)
LeetCode
3 min read
tree dfs post-order

Problem#

Given the root of a binary tree and two nodes p and q, return their lowest common ancestor (LCA) — the deepest node having both as descendants (a node can be its own descendant).

Examples#

  • For [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 13.
  • p = 5, q = 45.

Constraints#

  • The number of nodes is in [2, 10^5]. Both p and q exist in the tree.

Approach#

Recursive search. Return the current node if it equals p or q. Recurse into left and right. If both return non-null, the current node is the LCA. Otherwise return whichever is non-null.

Solution#

Lowest Common Ancestor of a Binary Tree
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root || root == p || root == q) return root;
TreeNode* l = lowestCommonAncestor(root->left, p, q);
TreeNode* r = lowestCommonAncestor(root->right, p, q);
if (l && r) return root;
return l ? l : r;
}
};

Editorial#

The recursive contract: each call returns the LCA within its subtree if both targets exist there, otherwise the single target found, otherwise null. Whenever a node receives non-null from both subtrees, it sits between p and q and is the LCA.

Complexity#

  • Time: O(n).
  • Space: O(h).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.