[Lintcode] Problem 854 - Closest Leaf in a Binary Tree

Given a binary tree where every node has a unique value, and a target key k.

Find the value of the nearest leaf node to target k in the tree. If there are multiple cases, you should follow these priorities:

  1. The leaf node is in the left subtree of the node with k;
  2. The leaf node is in the right subtree of the node with k;
  3. The leaf node is not in the subtree of the node with k.

Note

  1. root represents a binary tree with at least 1 node and at most 1000 nodes.
  2. Every node has a unique node.val in range [1, 1000].
  3. There exists a node in the given binary tree for which node.val == k.

Example

No.1

Input: {1, 3, 2}, k = 1

Output: 3

Explanation:

1
2
3
  1
/ \
3 2

No.2

Input: {1}, k = 1

Output: 1

Code

1
2
3
4
5
6
7
8
9
10
11
12
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
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
49
50
private TreeNode start;
private Map<TreeNode, TreeNode> connection = new HashMap<>();

public int findClosestLeaf(TreeNode root, int k) {
Set<TreeNode> visit = new HashSet<>();
Queue<TreeNode> queue = new LinkedList<>();

dfs(null, root, k);
queue.offer(start);
visit.add(start);

while (!queue.isEmpty()) {
TreeNode node = queue.poll();

if (node.left == null && node.right == null)
return node.val;

if (node.left != null && !visit.contains(node.left)) {
queue.offer(node.left);
visit.add(node.left);
}

if (node.right != null && !visit.contains(node.right)) {
queue.offer(node.right);
visit.add(node.right);
}

if (connection.containsKey(node) && !visit.contains(connection.get(node))) {
queue.offer(connection.get(node));
visit.add(connection.get(node));
}
}

return 0;
}

private void dfs(TreeNode parent, TreeNode node, int k) {
if (node == null)
return;

if (node.val == k)
start = node;

if (parent != null) {
connection.put(node, parent);
}

dfs(node, node.left, k);
dfs(node, node.right, k);
}