Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down * to the nearest leaf node.
Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down * to the nearest leaf node.
层次遍历法
public class MinimumDepthOfBinaryTree {
static boolean isLeaf(TreeNode root){
if(root.left == null && root.right == null){
return true;
}
return false;
}
public static int run(TreeNode root) {
if(root != null){
TreeNode temRoot;
int count = 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
root.val = 1;
while(queue.size() != 0){
temRoot = queue.poll();
int layer = temRoot.val;
if(isLeaf(temRoot)){
return layer;
}
if(temRoot.left != null){
queue.add(temRoot.left);
temRoot.left.val = temRoot.val + 1;
}
if(temRoot.right != null){
queue.add(temRoot.right);
temRoot.right.val = temRoot.val + 1;
}
}
}
return 0;
}
private static void build(TreeNode root) {
// TODO Auto-generated method stub
setLeft(root);
setRight(root);
setLeft(root.left);
setLeft(root.right);
}
public static void setLeft(TreeNode root){
root.left = new TreeNode(0);
}
public static void setRight(TreeNode root){
root.right = new TreeNode(0);
}
//运用层次遍历计算
public static void main(String[] args) {
TreeNode treeNode = new TreeNode(0);
build(treeNode);
System.out.println(run(treeNode));;
}