【LeetCode】863. All Nodes Distance K in Binary Tree 解题报告(Python)
【LeetCode】863. All Nodes Distance K in Binary Tree 解题报告(Python)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/description/
题目描述:
We are given a binary tree (with root node root), a target node, and an integer value K.
Return a list of the values of all nodes that have a distance K from the target node. The answer can be returned in any order.
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2
Output: [7,4,1]
Explanation:
The nodes that are a distance 2 from the target node (with value 5)
have values 7, 4, and 1.
Note that the inputs "root" and "target" are actually TreeNodes.
The descriptions of the inputs above are just serializations of these objects.
Note:
- The given tree is non-empty.
- Each node in the tree has unique values 0 <= node.val <= 500.
- The target node is a node in the tree.
- 0 <= K <= 1000.
题目大意
找出距离二叉树上某个节点距离为target的所有节点。注意不仅要向下寻找,还可以通过父亲节点反向寻找。
解题方法
第一眼看到这个题就感觉到这个题是个BFS问题,因为是满足条件的搜索问题,而且同时向不同方向寻找,找到之后提前终止。很像刚做过的,752. Open the Lock 。
所以这个题的做法就是通过DFS建立一个邻接矩阵,然后在这个邻接矩阵上使用BFS。这个BFS的做法和752题基本雷同,只是终止条件不同。
代码如下:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def distanceK(self, root, target, K):
"""
:type root: TreeNode
:type target: TreeNode
:type K: int
:rtype: List[int]
"""
# DFS
conn = collections.defaultdict(list)
def connect(parent, child):
if parent and child:
conn[parent.val].append(child.val)
conn[child.val].append(parent.val)
if child.left: connect(child, child.left)
if child.right: connect(child, child.right)
connect(None, root)
# BFS
que = collections.deque()
que.append(target.val)
visited = set([target.val])
for k in range(K):
size = len(que)
for i in range(size):
node = que.popleft()
for j in conn[node]:
if j not in visited:
que.append(j)
visited.add(j)
return list(que)
参考大神的BFS的写法,感觉醍醐灌顶啊!
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def distanceK(self, root, target, K):
"""
:type root: TreeNode
:type target: TreeNode
:type K: int
:rtype: List[int]
"""
# DFS
conn = collections.defaultdict(list)
def connect(parent, child):
if parent and child:
conn[parent.val].append(child.val)
conn[child.val].append(parent.val)
if child.left: connect(child, child.left)
if child.right: connect(child, child.right)
connect(None, root)
# BFS
bfs = [target.val]
visited = set([target.val])
for k in range(K):
bfs = [y for x in bfs for y in conn[x] if y not in visited]
visited |= set(bfs)
return bfs
参考资料:
日期
2018 年 9 月 14 日 ———— 现在需要的还是夯实基础,算法和理论
【LeetCode】863. All Nodes Distance K in Binary Tree 解题报告(Python)的更多相关文章
- leetcode 863. All Nodes Distance K in Binary Tree
We are given a binary tree (with root node root), a target node, and an integer value K. Return a li ...
- [Leetcode] 863. All Nodes Distance K in Binary Tree_ Medium tag: BFS, Amazon
We are given a binary tree (with root node root), a target node, and an integer value `K`. Return a ...
- 863. All Nodes Distance K in Binary Tree 到制定节点距离为k的节点
[抄题]: We are given a binary tree (with root node root), a target node, and an integer value K. Retur ...
- [LC] 863. All Nodes Distance K in Binary Tree
We are given a binary tree (with root node root), a target node, and an integer value K. Return a li ...
- 863. All Nodes Distance K in Binary Tree
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode ...
- [LeetCode] All Nodes Distance K in Binary Tree 二叉树距离为K的所有结点
We are given a binary tree (with root node root), a target node, and an integer value K. Return a li ...
- LeetCode – All Nodes Distance K in Binary Tree
We are given a binary tree (with root node root), a target node, and an integer value K. Return a li ...
- [Swift]LeetCode863. 二叉树中所有距离为 K 的结点 | All Nodes Distance K in Binary Tree
We are given a binary tree (with root node root), a targetnode, and an integer value K. Return a lis ...
- 【LeetCode】958. Check Completeness of a Binary Tree 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 BFS DFS 日期 题目地址:https://le ...
随机推荐
- 使用SpringBoot实现文件的下载
上一篇博客:使用SpringBoot实现文件的上传 已经实现了文件的上传,所以紧接着就是下载 首先还是html页面的简单设计 <form class="form-signin" ...
- 零基础学习java------33---------http协议,tomcat(其如何在eclipse上发布),注册案例
一. HTTP协议 https://www.cnblogs.com/vamei/archive/2013/05/11/3069788.html 二. tomcat---------->web服务 ...
- 13个酷炫的JavaScript一行程序
1. 获得一个随机的布尔值(true/false) const randomBoolean = () => Math.random() >= 0.5; console.log(random ...
- C++ 成绩排名
1004 成绩排名 (20分) 读入 n(>)名学生的姓名.学号.成绩,分别输出成绩最高和成绩最低学生的姓名和学号. 输入格式: 每个测试输入包含 1 个测试用例,格式为 第 1 行:正整数 ...
- Linux 设置时区
一.查看和修改Linux的时区 1. 查看当前时区命令 : "date -R" 2. 修改设置Linux服务器时区方法 A命令 : "tzselect" 方法 ...
- 解决springboot序列化 json数据到前端中文乱码问题
前言 关于springboot乱码的问题,之前有文章已经介绍过了,这一篇算是作为补充,重点解决对象在序列化过程中出现的中文乱码的问题,以及后台报500的错误. 问题描述 spring Boot 中文返 ...
- Swift Storyboard找不到类文件
Swift语言引入了Module概念,在通过关键字@objc(类名)做转换的时候,由于Storyboard没有及时更新Module属性,会导致如下两种类型错误: 1 用@objc(类名)标记的Swif ...
- GO 定时器NewTimer、NewTicker使用
package main import ( "fmt" "sync" "time" ) /** *ticker只要定义完成,从此刻开始计时, ...
- table表格数据无缝循环滚动
分享一个好看的表格无缝滚动:(实战用起来很舒服) 直接copy代码到你的程序中: 1.HTML <div class="tablebox"> ...
- linux基本操作命令2
复制文件 格式: cp [参数] [ 被复制的文件路径] [ 复制的文件路径] -r :递归复制 (需要复制文件夹时使用) 案例:将/root目录下的test文件夹及其内部的文件复制到/tmp中 [ ...