求给定二叉树的最小深度。最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量。
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 {
int minDepth = Integer.MAX_VALUE;
void help(TreeNode root, int depth){
if(root.left == null && root.right == null){
if(depth < minDepth)
minDepth = depth;
}else{
if(root.left != null)
help(root.left, depth+1);
if(root.right != null)
help(root.right, depth+1);
}
}
public int run(TreeNode root) {
if(root == null)return 0;
else{
help(root, 1);
return minDepth;
}
}
}先参考下面的这个思路完成这道题目,应该是可以的,这种思路也是我在追求实现的,因为理解起来比较直观。
来个非递归的,思路是层序遍历,找到第一个左右结点都为null的情况,就返回
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
public int run(TreeNode root) {
if(root == null)



京公网安备 11010502036488号