Lowest Common Ancestor of a Binary Tree
Tree
Medium
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).”
Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]
_______3______
/ \
___5__ ___1__
/ \ / \
6 _2 0 8
/ \
7 4Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of of nodes 5 and 1 is 3.Example 2:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself
according to the LCA definition.Note:
All of the nodes' values will be unique.
p and q are different and both values will exist in the binary tree.
Analysis
Recursive
The node which is the lowest common ancestor will have paths to both two given nodes, thus we can return the targeted node if we find them in the traversal. And return the node itself when both its left and right child tree return non-null node, which means it's the LCA node itself, or, return the non-null node from either left or right of its child.
Iterative
To find the lowest common ancestor, we need to find where is
pandqand a way to track their ancestors. Aparentpointer for each node found is good for the job. After we found bothpandq, we create a set ofp'sancestors. Then we travel throughq'sancestors, the first one appears inp's is our answer.
Divide & Conquer (by @si)
Goal: given the root, find LCA ==> see root.left & root.right, having LCA or not ==> Then get answer on root
Divide
Conquer - four cases
Solution
Recursive
*Favorite
Verbose Recursion - (Most Easy to Understand Though)
Iterative - using parent pointers
If we have parent pointers for each node we can traverse back from p and q to get their ancestors. The first common node we get during this traversal would be the LCA node. We can save the parent pointers in a dictionary as we traverse the tree.
Iterative - with comments
Reference
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/solution/
Last updated
Was this helpful?