[LeetCode] Problem 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

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.

eMaYZV.png

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.

Code

1
2
3
4
5
6
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
List<Integer> result = new ArrayList<>();
helper(result, root, target, K);
return result;
}

private int helper(List<Integer> result, TreeNode root, TreeNode target, int K) {
if (root == null)
return -1;

if (root == target) {
collect(result, root, K);
return 0;
}

int left = helper(result, root.left, target, K);
int right = helper(result, root.right, target, K);

if (left >= 0) {
if (left + 1 == K)
result.add(root.val);

collect(result, root.right, K - left - 2);
return left + 1;
}
else if (right >= 0) {
if (right + 1 == K)
result.add(root.val);

collect(result, root.left, K - right - 2);
return right + 1;
}
else
return -1;
}

private void collect(List<Integer> result, TreeNode root, int K) {
if (root == null || K < 0)
return;

if (K == 0) {
result.add(root.val);
return;
}

collect(result, root.left, K - 1);
collect(result, root.right, K - 1);
}