递归or存储父节点_236_二叉树的最近公共祖先

题目描述

在这里插入图片描述

思路

方法一:递归

在这里插入图片描述

# Definition for a binary tree node.
# 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':
           
        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节点自身
# Definition for a binary tree node.
# 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':
        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:  # 遍历完两个target node之后,提前退出循环,more efficiency
                break
        # for k, v in data_dict.items():
        #     print(k.val, v.val)
        # print(len(data_dict))

        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]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值