leetcode 236. Lowest Common Ancestor of a Binary Tree

17 篇文章 0 订阅
14 篇文章 0 订阅

题目

给定一棵二叉树,找到给定的两个结点的最低共同祖先(LCA)。
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/198584/Python-BFS-with-English-and-Chinese-explanation

思路

宽度优先搜索二叉树,使用一个字典parent记录每一对父子关系,设置早停标志flag,找到两个目标结点后就停止。然后通过父子关系字典构建一个列表list1一个集合set2,list1是其中一个结点到根节点的路径,是有顺序的,set2是另一个结点到根节点的路径包含的结点。逐个遍历list1,如果当前元素在set2中,该元素就是LCA。

代码

# 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, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        if root == p or root == q:
            return root
        from collections import deque
        parent = {}
        flag = 0
        queue = deque()
        queue.append(root)
        # parent[root] = root
        while len(queue):
            temp = queue.popleft()
            if temp.left:
                parent[temp.left] = temp
                queue.append(temp.left)
                if temp.left.val == p.val or temp.left.val == q.val:
                    flag += 1
            if temp.right:
                parent[temp.right] = temp
                queue.append(temp.right)
                if temp.right.val == p.val or temp.right.val == q.val:
                    flag += 1
            if flag == 2:
                break

        list1 = [p]
        temp = p
        while temp.val != root.val:
            list1.append(parent[temp])
            temp = parent[temp]
        set2 = {q}
        temp = q
        while temp.val != root.val:
            set2.add(parent[temp])
            temp = parent[temp]

        for i in list1:
            if i in set2:
                return i
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值