Leetcode236. Lowest Common Ancestor of a Binary Tree
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]
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA 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.
思路
-
两个节点p,q分为两种情况:p和q在相同子树中,p和q在不同子树中
-
从根节点遍历,递归向左右子树查询节点信息
- 递归终止条件:如果当前节点为空或等于
p
或q
,则返回当前节点。 - 递归遍历左右子树,如果左右子树查到节点都不为空,则表明
p
和q
分别在左右子树中,因此,当前节点即为最近公共祖先; - 如果左右子树其中一个不为空,则返回非空节点。
- 递归终止条件:如果当前节点为空或等于
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 && right) return root;
return left ? left : right;
}
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
# If looking for me, return myself
if root == p or root == q:
return root
left = right = None
# else look in left and right child
if root.left:
left = self.lowestCommonAncestor(root.left, p, q)
if root.right:
right = self.lowestCommonAncestor(root.right, p, q)
# if both children returned a node, means
# both p and q found so parent is LCA
if left and right:
return root
else:
# either one of the chidren returned a node, meaning either p or q found on left or right branch.
# Example: assuming 'p' found in left child, right child returned 'None'. This means 'q' is
# somewhere below node where 'p' was found we dont need to search all the way,
# because in such scenarios, node where 'p' found is LCA
return left or right
DFS
Simply use DFS
to search for p
and q
, and record their paths once hit, then just compare the two paths and you will find the lowest common ancestor!
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
stack, p_trace, q_trace = [], [], []
while True:
if root.left:
stack.append(root)
root.left, root = None, root.left
elif root.right:
stack.append(root)
root.right, root = None, root.right
else:
if root is p:
p_trace = stack[:]
p_trace.append(root)
if root is q:
q_trace = stack[:]
q_trace.append(root)
if p_trace and q_trace:
break
root = stack.pop()
i, m = 0, min(len(p_trace), len(q_trace))
while i < m and p_trace[i] is q_trace[i]:
ans = p_trace[i]
i += 1
return ans