题目:
给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 说明:叶子节点是指没有子节点的节点。
示例:
输入:root = [3,9,20,null,null,15,7] 输出:2
思路:
一定注意,叶子节点是没有子节点的节点。所以只是简单地把《二叉树的最大深度》中,左右子树取最大深度改成取最小深度是不对的。
/** * 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; }else{ return getDepth(root.left,root.right); } } public int getDepth(TreeNode left,TreeNode right){//1.确定参数和返回值 int count=1; if(left==null&&right==null){//2.确定终止条件:当左右孩子为空时,才是叶子节点 return count; } if(left!=null&&right==null){ count=getDepth(left.left,left.right)+1; } if(left==null&&right!=null){ count=getDepth(right.left,right.right)+1; } if(left!=null&&right!=null){ int count1=getDepth(left.left,left.right)+1;//3.确定单层逻辑 int count2=getDepth(right.left,right.right)+1; count=count1<count2?count1:count2;//返回更小的深度值 } return count; } }
标签:right,TreeNode,int,力扣,111,二叉树,null,节点,left From: https://www.cnblogs.com/cjhtxdy/p/17069551.html