题目
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 TreeNode {
public int val;
public TreeNode left, right;
public TreeNode(int val) {
this.val = val;
this.left = this.right = null;
}
}
层序遍历实现求最小深度:
public class Solution {
/**
* @param root: The root of binary tree
* @return: An integer
*/
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}
//用于记录遍历层数
int min = 0;
LinkedList<TreeNode> l1 = new LinkedList<TreeNode>();
LinkedList<TreeNode> l2 = new LinkedList<TreeNode>();
l1.add(root);
while(!l1.isEmpty() || !l2.isEmpty()){
min++;
if(l2.isEmpty()){
while(!l1.isEmpty()){
TreeNode n = l1.poll();
//左右节点都为空,即认为找到了最小深度
if(n.left == null && n.right == null){
return min;
}
if(n.left!=null){
l2.add(n.left);
}
if(n.right!=null){
l2.add(n.right);
}
}
}else{
while(!l2.isEmpty()){
TreeNode n = l2.poll();
if(n.left == null && n.right == null){
return min;
}
if(n.left!=null){
l1.add(n.left);
}
if(n.right!=null){
l1.add(n.right);
}
}
}
}
return min;
}
}