Given the root of a binary tree, find the closest leaf node to the root. A leaf node is any node that does not have any children (both left and right are null).
Input:1/\23/\45 Output:2 Explanation: Node `2`is a closest leaf to the root(distance =1). Nodes `4` and `5` are also leaf nodes but farther(distance =2 from root).
Input:10/\812\9 Output:9 Explanation: Node `9`is the closest leaf to root(distance =2), whereas node `12`is farther (distance =1 from root in different direction).
publicclassSolution {
publicintclosestLeafFromRoot(TreeNode root) {
// Edge case: Empty treeif (root ==null) {
return-1; // Return -1 to indicate tree does not exist }
// BFS traversal using a queue Queue<TreeNode> queue =new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
// Extract the current node TreeNode node = queue.poll();
// If it's a leaf node, return its valueif (node.left==null&& node.right==null) {
return node.val;
}
// Otherwise, enqueue its childrenif (node.left!=null) {
queue.add(node.left);
}
if (node.right!=null) {
queue.add(node.right);
}
}
return-1; // This will never be reached if tree is valid }
}