import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
public static int depth = Integer.MAX_VALUE;
public int minDepth (TreeNode root) {
// write code here
if(root==null){
return 0;
}
search(root, 0);
return depth;
}
public void search(TreeNode root, int cur) {
if(root==null){
return;
}
if (root.left == null && root.right==null) {
depth = Math.min(cur+1, depth);
return;
}
search(root.left, cur + 1);
search(root.right, cur + 1);
}
}
本题考察的知识点主要是二叉树的遍历操作和叶子结点的判定,所用编程语言为java.
本题跟之前求二叉树最长路径有异曲同工之妙,只不过一个求最长路径,一个求最短路径,解法都是一样的

京公网安备 11010502036488号