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:

  1. The given tree is non-empty.
  2. Each node in the tree has unique values 0 <= node.val <= 500.
  3. The target node is a node in the tree.
  4. 0 <= K <= 1000.

经典的BFS, 其实跟之前做的employee importance很像, 只不过这个是tree, 那个是已经做好的列表, 但是我们可以用helper函数来讲tree 转换为一个undirected graph, 就是一个dictionary, 然后就用经典的BFS, 只不过append queue时, 要append进去id 和当前的distance. 注意一点的是edge case, k == 0, return [target.val], 其他时候是不包括target.val的.不过因为最开始visited已经有了target.val, 所以好像可以将判断node != target.val去掉. 经过验证, 确实是不需要这一步了.

1. constraints

1) tree not empty

2) node.val is unique

3) target always in tree

4) 0 <= K <= 1000, edge case, K== 0 , 直接return target.val

2. ideas

BFS :     T: O(n)     S: O(n)   n: number of nodes

1. edge

2. 将tree 转换为dictionary

3. 用常规的BFS的做法, 只不过append queue时, 要append进去id 和当前的distance.

3. code

 class Solution:
def distancek(self, root, target, K):
if K == 0: return [target.val]
helper(root):
if root:
if root.left:
d[root.val].add(root.left.val)
d[root.left.val].add(root.val)
helper(root.left)
if root.right:
d[root.val].add(root.right.val)
d[root.right.val].add(root.val)
helper(root.right)
d= collections.defaultdict(set)
helper(root)
queue, visited, ans = collections.deque([(target.val, 0)]), set([target.val]), [] # notice 不能直接用set(target.val), 因为要用iterable的parameter
while queue:
node, dis = queue.popleft()
if dis == K:
ans.append(node)
elif dis < K:
for each in d[node]:
if each not in visited:
queue.append((each, dis+1))
visited.add(each)
return ans

4. test cases

用例子里面的cases即可.

[Leetcode] 863. All Nodes Distance K in Binary Tree_ Medium tag: BFS, Amazon的更多相关文章

  1. 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 ...

  2. 【LeetCode】863. All Nodes Distance K in Binary Tree 解题报告(Python)

    [LeetCode]863. All Nodes Distance K in Binary Tree 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http ...

  3. 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 ...

  4. [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 ...

  5. 863. All Nodes Distance K in Binary Tree

    /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode ...

  6. [LeetCode] 236. Lowest Common Ancestor of a Binary Tree_ Medium tag: DFS, Divide and conquer

    Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According ...

  7. [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 ...

  8. 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 ...

  9. [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 ...

随机推荐

  1. JS-几大排序算法(更新中...)

    关于排序都会讲的名词:(我自己的理解) 时间复杂度: 指排序过程中,程序消耗的时间. 空间复杂度: 指排序过程中,程序所消耗内存的大小. 稳定: 如果两个值相等,a和b,a=b且a在b位置的左边,排序 ...

  2. MFC 刷新函数:Invaldate,UpdateWindow,InvaldateRect

    在窗口刷新和绘制的过程中,常常需要用到窗口刷新函数.一般用于窗口图形刷新的函数有:UpdateWindows().Invaldate().InvaldateRect(). 先说UpdateWindow ...

  3. gerrit_bash_commands.sh

    https://github.com/tomwys/gerrit-bash-commands gerrit_bash_commands.sh # Author: Tomasz Wysocki < ...

  4. Oracle相关内容整理

    一.常用sql 1.查看版本 SELECT * FROM V$VERSION; SELECT version FROM V$INSTANCE 2.数据库发生死锁时,跟踪文件的位置 关于跟踪文件,大义是 ...

  5. gitlab无法push或clone的错误:JWT::DecodeError (Nil JSON web token): lib/gitlab/workhorse.rb:120:in `verify_api_request!'

    使用源码安装的方式升级gitlib7.14到gitlab-8.13.5中文版,然后push的时候报错: 错误信息如下: Started GET "/gitlab/hushizhi/gitla ...

  6. EJBCA的安装(基于Ubuntu 16.04 LTS + wildfly8 + ejbca6.3.11 + jdk7)

    前一段时间折腾了一下PKI,用EJBCA在研究院内网搭建了一个CA,目前是提供给手机端(安卓和IOS)来和服务器端(nginx + Java应用)做安全连接的(客户端和服务器端双向认证) 由于EJBC ...

  7. Unity3D笔记 英保通二

    一.访问另一个物体 1.代码中定义一个public的物体 例如:var target:Transform; 在面板上直接拖拽一个物体赋值给target 2.通过GameObject.Find(&quo ...

  8. oracle如何设置表空间autoextensible自动扩容

    SELECT a.tablespace_name "表空间名", total / 1024 / 1024 "表空间大小单位M", free / 1024 / 1 ...

  9. Spark ML包,数据挖掘示例数据Affairs

    1.数据字段解释 affairs:一年来婚外情的频率   gender:性别   age:年龄   yearsmarried:婚龄   children:是否有小孩   religiousness:宗 ...

  10. 转Python SciPy库——拟合与插值

    1.最小二乘拟合 实例1 import numpy as np import matplotlib.pyplot as plt from scipy.optimize import leastsq p ...