知识点
树,递归
解题思路
递归传入前面递归过的节点数目,当前的节点数目就等于前面节点数目+1,当左右子树都为空也就是叶子节点时去更新最少的节点数目。
java题解
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整型
*/
int ans = Integer.MAX_VALUE;
public int minDepth (TreeNode root) {
// write code here
if(root == null) return 0;
fun(root,0);
return ans;
}
public void fun(TreeNode root,int pre){
int num = pre + 1;
if(root.left == null && root.right == null){
ans = Math.min(ans,num);
}
if(root.left != null){
fun(root.left,pre + 1);
}
if(root.right != null){
fun(root.right,pre + 1);
}
}
}



京公网安备 11010502036488号