No236. The nearest common ancestor of a binary tree
topic
Given a binary tree, find the nearest common ancestor of two specified nodes in the tree.
The definition of the nearest common ancestor in Baidu Encyclopedia is: "For the two nodes p and q of the rooted tree T, the nearest common ancestor is expressed as a node x, so that x is the ancestor of p and q and the depth of x is as large as possible (A node can also be its own ancestor)."
For example, given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]
Example 1
- Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
- Output: 3
- Explanation: The nearest common ancestor of node 5 and node 1 is node 3.
Example 2
- Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
- Output: 5
- Explanation: The nearest common ancestor of node 5 and node 4 is node 5. Because by definition the nearest common ancestor node can be the node itself.
Description:
- The values of all nodes are unique.
- p and q are different nodes and both exist in the given binary tree.
Ideas
Using recursive thinking, consider the following operations:
- If the current node is empty and the value is equal to the value of p or q, it returns root;
- Otherwise, the left and right subtrees are recursively called to determine whether there is a result, p, q, and root have the following three relationships:
- [0,2], [1,1], [2,0], considering the first case, left must be empty, just return right; considering the third case, right must be empty, just return left; In the second case, both left and right are non-empty, just return to root directly.
Problem-solving code (Python3)
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root or root.val in [p.val,q.val]:
return root
left = self.lowestCommonAncestor(root.left,p,q)
right = self.lowestCommonAncestor(root.right,p,q)
if not left:
return right
if not right:
return left
return root
Complexity analysis:
- The time complexity is O(n). The worst is to traverse all the nodes and drop the constant.
- Space complexity O(n) requires additional space to store the stack