742 Closest Leaf in a Binary Tree

1. Question

Given a binary tree where every node has a unique value, and a target keyk, find the value of the nearest leaf node to targetkin the tree.
Here,nearestto a leaf means the least number of edges travelled on the binary tree to reach any leaf of the tree. Also, a node is called aleafif it has no children.
In the following examples, the input tree is represented in flattened form row by row. The actualroottree given will be a TreeNode object.
Example 1:
1
Input: root = [1, 3, 2], k = 1
2
Diagram of binary tree:
3
1
4
/ \
5
3 2
6
7
8
Output: 2 (or 3)
9
10
Explanation: Either 2 or 3 is the nearest leaf node to the target of 1.
Copied!
Example 2:
1
Input: root = [1], k = 1
2
3
Output: 1
4
5
6
Explanation: The nearest leaf node is the root node itself.
Copied!
Example 3:
1
Input: root = [1,2,3,4,null,null,null,5,null,6], k = 2
2
Diagram of binary tree:
3
1
4
/ \
5
2 3
6
/
7
4
8
/
9
5
10
/
11
6
12
13
14
Output: 3
15
16
Explanation:
17
The leaf node with value 3 (and not the leaf node with value 6) is nearest to the node with value 2.
Copied!
Note:
  1. 1.
    rootrepresents a binary tree with at least1node and at most1000nodes.
  2. 2.
    Every node has a uniquenode.valin range[1, 1000].
  3. 3.
    There exists some node in the given binary tree for whichnode.val == k.

2. Implementation

(1) DFS + BFS
思路: 1. DFS to construct graph
  1. 1.
    BFS to find the closet leaf node
1
class Solution {
2
public int findClosestLeaf(TreeNode root, int k) {
3
TreeNode[] start = new TreeNode[1];
4
Map<TreeNode, List<TreeNode>> adjList = new HashMap<>();
5
buildGraph(root, null, k, start, adjList);
6
7
Queue<TreeNode> queue = new LinkedList<>();
8
queue.add(start[0]);
9
10
Set<TreeNode> visited = new HashSet<>();
11
12
while (!queue.isEmpty()) {
13
int size = queue.size();
14
15
for (int i = 0; i < size; i++) {
16
TreeNode curNode = queue.remove();
17
visited.add(curNode);
18
19
if (curNode.left == null && curNode.right == null) {
20
return curNode.val;
21
}
22
23
for (TreeNode nextNode : adjList.get(curNode)) {
24
if (!visited.contains(nextNode)) {
25
queue.add(nextNode);
26
}
27
}
28
}
29
}
30
return -1;
31
32
}
33
34
public void buildGraph(TreeNode curNode, TreeNode parent, int k, TreeNode[] start, Map<TreeNode, List<TreeNode>> adjList) {
35
if (curNode == null) {
36
return;
37
}
38
39
if (curNode.val == k) {
40
start[0] = curNode;
41
}
42
43
if (parent != null) {
44
adjList.putIfAbsent(curNode, new ArrayList<>());
45
adjList.putIfAbsent(parent, new ArrayList<>());
46
adjList.get(curNode).add(parent);
47
adjList.get(parent).add(curNode);
48
}
49
50
buildGraph(curNode.left, curNode, k, start, adjList);
51
buildGraph(curNode.right, curNode, k, start, adjList);
52
}
53
}
Copied!

3. Time & Space Complexity

DFS + BFS : 时间复杂度O(n), 空间复杂度O(n)