111. Minimum Depth of Binary Tree
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 Solution {
public int minDepth(TreeNode root) {
if (root == null)
return 0;
int depth = 1;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
TreeNode temp,magic = new TreeNode(0);
queue.add(root);
queue.add(magic);
while(!queue.isEmpty()){
temp = queue.poll();
if(temp.equals(magic)){
if(!queue.isEmpty()){
depth++;
queue.add(magic);
}
continue;
}
if(temp.left == null && temp.right == null)
return depth;
if(temp.left != null)
queue.add(temp.left);
if(temp.right != null)
queue.add(temp.right);
}
return depth;
}
}
上述程序使用了层次遍历的方法,运用了遍历操作。不理解,这里的层次遍历是如何用的,并且二叉树是如何与队列相联系的。
To be continue……