【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 ...
随机推荐
- perl练习——计算点突变
题目来源:http://rosalind.info/problems/hamm/ 一.程序目的:计算序列点突变(Point Mutations) 输入: GAGCCTACTAACGGGAT CATCG ...
- SQL-Union、Union ALL合并两个或多个 SELECT 语句的结果集
UNION 操作符用于合并两个或多个 SELECT 语句的结果集. 请注意,UNION 内部的 SELECT 语句必须拥有相同数量的列.列也必须拥有相似的数据类型.同时,每条 SELECT 语句中的列 ...
- Excel—在Excel中利用宏定义实现MD5对字符串(如:手机号)或者文件加密
下载宏文件[md5宏] 加载宏 试验md5加密 可能遇到的问题 解决办法 下载宏文件[md5宏] 下载附件,解压,得md5宏.xla md5宏.zip 加载宏 依次打开[文件]-[选项]-[自定义功能 ...
- C#表格,表格信息、GridView使用。
page: <%@ Control Language="C#" AutoEventWireup="true" CodeFile="test1.a ...
- 日常Java 2021/11/18
用idea实现Javaweb登录页面 <%-- Created by IntelliJ IDEA. User: Tefuir Date: 2021/11/18 Time: 18:14 To ch ...
- PhoneGap本地将html打包成安卓App
PhoneGap的在线打包有大小限制,超过30M的包无法在线打包.当然,可以把包里面的图片.声音文件去掉,然后打包.下载以后,解包,重新打包并签名.蛮麻烦的. 本地打包的简单方法如下: 下载安装Jav ...
- MyBatis(2):CRUD操作
编写接口 import com.shandx.pojo.User; import java.util.List; public interface UserMapper { <span clas ...
- linux网络相关命令之脚本和centos启动流程
nice 功用:设置优先权,可以改变程序执行的优先权等级.等级的范围从-19(最高优先级)到20(最低优先级).优先级为操作系统决定cpu分配的参数,优先级越高,所可能获得的 cpu时间越长. 语法: ...
- Js判断数组中是否存在某个元素
Js判断数组中是否存在某个元素 方法一:indexOf(item,start); Item:要查找的值:start:可选的整数参数,缺省则从起始位子开始查找. indexOf();返回元素在数组中的位 ...
- java通过JDBC访问数据库(最基本的查询)
一.步骤介绍 1.通过Class.forName()加载驱动: 2.通过DriverManager.getConnection()获取Conncetion连接对象: 3.创建Statement对象传递 ...