给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
解法:bfs
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.LinkedList;
import java.util.Queue;
class Solution {
class Node{
TreeNode node;
int depth;
public Node(TreeNode node,int depth){
this.node = node;
this.depth = depth;
}
}
public int minDepth(TreeNode root) {
return bfs(root);
}
public int bfs(TreeNode root){
if(root == null){
return 0;
}
Queue<Node> queue = new LinkedList<Node>();
queue.add(new Node(root,1));
while(!queue.isEmpty()){
Node head = queue.poll();
if(head.node.left != null){
queue.add(new Node(head.node.left,head.depth+1));
}
if(head.node.right != null){
queue.add(new Node(head.node.right,head.depth+1));
}
if(head.node.right == null && head.node.left == null){
return head.depth;
}
}
return 0;
}
}