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

[LeetCode] 863. All Nodes Distance K in Binary Tree

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.

二叉树中所有距离为 K 的结点。

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/all-nodes-distance-k-in-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题非常好,是一道树 tree 和图论 graph 的结合题。这里我提供一个 BFS 的做法。

题目给的 input 是树,但是我们是需要把他转译成图才能做的,这样我们才能既可以知道父节点的邻居有子节点,也可以知道子节点的邻居有父节点。知道这些信息之后,我们从 target 节点开始做 BFS 遍历。因为题目找的是距离 target 节点长度为 K 的节点,所以我们在开始 BFS 遍历的同时,要记得 K--。这样当 K = 0 的时候,如果此时 queue 中有元素,这些元素就都是相距 target 节点,距离为 K 的节点。

时间O(n)

空间O(n)

Java实现

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     HashMap<TreeNode, List<TreeNode>> map = new HashMap<>();
12     
13     public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
14         List<Integer> res = new ArrayList<>();
15         
16         // build the graph
17         buildGraph(root, null);
18         
19         // corner case
20         if (!map.containsKey(target)) {
21             return res;
22         }
23         
24         HashSet<TreeNode> visited = new HashSet<>();
25         Queue<TreeNode> queue = new LinkedList<>();
26         visited.add(target);
27         queue.offer(target);
28         while (!queue.isEmpty()) {
29             int size = queue.size();
30             // 抵达终点
31             if (K == 0) {
32                 for (int i = 0; i < size; i++) {
33                     TreeNode cur = queue.poll();
34                     res.add(cur.val);
35                 }
36                 return res;
37             }
38             
39             // 在路上
40             for (int i = 0; i < size; i++) {
41                 TreeNode cur = queue.poll();
42                 for (TreeNode next : map.get(cur)) {
43                     if (visited.contains(next)) {
44                         continue;
45                     }
46                     visited.add(next);
47                     queue.offer(next);
48                 }
49             }
50             K--;
51         }
52         return res;
53     }
54     
55     // 类似前序遍历的方式创建图
56     private void buildGraph(TreeNode node, TreeNode parent) {
57         // base case
58         if (node == null) {
59             return;
60         }
61         if (!map.containsKey(node)) {
62             map.put(node, new ArrayList<>());
63             if (parent != null) {
64                 map.get(node).add(parent);
65                 map.get(parent).add(node);
66             }
67             buildGraph(node.left, node);
68             buildGraph(node.right, node);
69         }
70     }
71 }

LeetCode 题目总结