Input: root = [1,2,3,4,null,null,null,5,null,6], k = 2 Diagram of binary tree: 1 / \ 2 3 / 4 / 5 / 6 Output: 3 Explanation: The leaf node with value 3 (and not the leaf node with value 6) is nearest to the node with value 2.
思路:把tree变换成图,建立图的过程,顺便把startNode找到;然后在图中做BFS,无向图,必须要有visited,否则会有死循环;
/**
* Definition for a binary tree node.
* 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;
* }
* }
*/
class Solution {
public int findClosestLeaf(TreeNode root, int k) {
HashMap<TreeNode, List<TreeNode>> graph = new HashMap<>();
TreeNode[] targetNode = new TreeNode[1];
buildGraph(graph, root, null, targetNode, k);
Queue<TreeNode> queue = new LinkedList<>();
HashSet<TreeNode> visited = new HashSet<>();
queue.offer(targetNode[0]);
visited.add(targetNode[0]);
while(!queue.isEmpty()) {
int size = queue.size();
for(int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if(node.left == null && node.right == null) {
return node.val;
}
for(TreeNode neighbor: graph.get(node)) {
if(!visited.contains(neighbor)) {
visited.add(neighbor);
queue.offer(neighbor);
}
}
}
}
return -1;
}
private void buildGraph(HashMap<TreeNode, List<TreeNode>> graph,
TreeNode root, TreeNode parent, TreeNode[] targetNode, int target) {
if(root == null) {
return;
}
if(root.val == target) {
targetNode[0] = root;
}
graph.putIfAbsent(root, new ArrayList<TreeNode>());
if(root.left != null) {
graph.get(root).add(root.left);
buildGraph(graph, root.left, root, targetNode, target);
}
if(root.right != null) {
graph.get(root).add(root.right);
buildGraph(graph, root.right, root, targetNode, target);
}
if(parent != null) {
graph.get(root).add(parent);
}
}
}