题目描述
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).”
解题思路
求两个节点的最低公共祖先。怎么刻画最低公共祖先呢?给定两个节点 p,q,我们用 Pp 和 Pq 表示从 root 节点到他们的路径,那么这两个路径的最大公共前缀就是从root节点到其最低公共祖先的路径。
代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import copy
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
self.p = p
self.q = q
self.path2p = []
self.path2q = []
self.helper(root, [])
bg = root
for i in range(min(len(self.path2p), len(self.path2q))):
if self.path2p[i] == self.path2q[i]:
if self.path2p[i] == 'l':
bg = bg.left
else:
bg = bg.right
else:
break
return bg
def helper(self, root, tmp):
if not root:
return
if root.val == self.q.val:
self.path2q = copy.deepcopy(tmp)
if root.val == self.p.val:
self.path2p = copy.deepcopy(tmp)
tmp.append('l')
self.helper(root.left, tmp)
tmp.pop()
tmp.append('r')
self.helper(root.right, tmp)
tmp.pop()