📅  最后修改于: 2023-12-03 15:22:00.588000             🧑  作者: Mango
在树结构中,我们经常需要找到两个节点的公共祖先或公共路径。本文将介绍一种从根或共同祖先开始打印路径上的公共节点的方法。
具体实现步骤如下:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
path_p, path_q = [], []
self.dfs(root, p, path_p)
self.dfs(root, q, path_q)
n = min(len(path_p), len(path_q))
for i in range(n):
if path_p[i] != path_q[i]:
return path_p[i-1]
return path_p[n-1]
def dfs(self, root, target, path):
if root == target:
path.append(root)
return True
if not root:
return False
path.append(root)
if self.dfs(root.left, target, path):
return True
if self.dfs(root.right, target, path):
return True
path.pop()
return False