题目描述
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1113916e18583c69b95e60a8e73570fe.png)
思路
方法一:递归
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/69e1bc3551bc1fefc151e86c8d6d2303.png)
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
def dfs(root, p, q):
if not root: return False
lson = dfs(root.left, p, q)
rson = dfs(root.right, p, q)
if (lson and rson) or ((root == p or root == q) and (lson or rson)):
self.res = root
return lson or rson or root == p or root == q
self.res = None
dfs(root, p, q)
return self.res
方法二:存储父节点
- 用
hash
字典存储每个节点的父节点 - 然后用
hash
集合 存储 p
节点 所有的父节点(祖先节点) – 这里集合中需要包括 p
节点自身 - 找
q
的父节点 (祖先节点),第一次出现在 p
的祖先节点集合中的节点 即为结果。-- 这里判断是也需要包括 q
节点自身
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
from collections import deque
queue = deque()
data_dict = {}
queue.append(root)
cnt = 0
while queue:
top = queue.popleft()
if top.left:
data_dict[top.left] = top
queue.append(top.left)
if top.right:
data_dict[top.right] = top
queue.append(top.right)
if top == p:
cnt += 1
if top == q:
cnt += 1
if cnt == 2:
break
fater_p = set()
fater_p.add(p)
while p in data_dict:
fater_p.add(data_dict[p])
p = data_dict[p]
while True:
if q in fater_p:
return q
else:
q = data_dict[q]