leetcode —— 863. 二叉树中所有距离为 K 的结点

给定一个二叉树(具有根结点 root), 一个目标结点 target ,和一个整数值 K 。

返回到目标结点 target 距离为 K 的所有结点的值的列表。 答案可以以任何顺序返回。

示例 1:

输入:root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2
输出:[7,4,1]
解释:
所求结点为与目标结点(值为 5)距离为 2 的结点,
值分别为 7,4,以及 1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/all-nodes-distance-k-in-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
——————————————
解题思路:
(1)使用深度优先遍历,对每个节点增加一个指向父结点的信息;这样就可以从目标节点基于广度优先遍历的方法从左子节点,右子节点,父节点进行广度优先遍历,得到距离为k的所有节点值。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def distanceK(self, root: TreeNode, target: TreeNode, K: int) -> List[int]:
        def dfs(root,val=None):  # 深度优先遍历,增加指向父节点的信息
            root.father = val
            if root.left:
                dfs(root.left,root)
            if root.right:
                dfs(root.right,root)
        dfs(root)
        
        queue = collections.deque([[target,0]])
        seed = set([target])
        while queue:  # 基于广度优先的深度遍历
            if queue[0][1]==K:
                return [node.val for node, d in queue]
            num,d = queue.popleft()
            if (num.left not in seed) and num.left:
                queue.append([num.left,d+1])
                seed.add(num.left)
            if (num.right not in seed) and num.right:
                queue.append([num.right,d+1])
                seed.add(num.right)
            if (num.father not in seed) and num.father:
                queue.append([num.father,d+1])
                seed.add(num.father)
        return []
发布了320 篇原创文章 · 获赞 21 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_37388085/article/details/105280102