JAVA版本
本题的思路与求最大深度相似,但是有有不同。
方法一: 递归
本题要求的是二叉树的最小深度,所以二叉树的终止条件发生改变,当只要左右结点只要有一个是空的时间就结束递归。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if (root ==null){
return 0;
}
int leftlength = minDepth(root.left);
int rightlength = minDepth(root.right);
//因为是找最小值,所以左右孩子只要有一个为空就返回值
if (root.left == null) {
return rightlength + 1;
}
if (root.right == null) {
return leftlength + 1;
}
int min = Math.min(leftlength,rightlength) +1;
return min;
}
}
方法二 :迭代法,使用队列来模拟存储的过程。
在每次遍历一层的时间,判断这个结点是不是叶子结点,如果是叶子结点的话就return,因为求的是最小长度。
class Solution {
public int minDepth(TreeNode root) {
if(root == null) {
return 0;
}
int depth =0;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()) {
int size = queue.size();
depth ++;
for (int i=0;i<size;i++){
TreeNode temp = queue.poll();
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;
}
}