一、题目名称
二、题目要求
三、相应举例
四、限制要求
五、解决办法
深度优先搜索
六、代码实现
LeetCode 111. 二叉树的最小深度
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:2
示例 2:
输入:root = [2,null,3,null,4,null,5,null,6]
输出:5
[0, 105]
内-1000 <= Node.val <= 1000
使用深度优先搜索的方法,遍历整棵树,记录最小深度。
对于每一个非叶子节点,我们只需要分别计算其左右子树的最小叶子节点深度。这样就将一个大问题转化为了小问题,可以递归地解决该问题。
class Solution {public int minDepth(TreeNode root) {if (root == null) {return 0;}if (root.left == null && root.right == null) {return 1;}int min_depth = Integer.MAX_VALUE;if (root.left != null) {min_depth = Math.min(minDepth(root.left), min_depth);}if (root.right != null) {min_depth = Math.min(minDepth(root.right), min_depth);}return min_depth + 1;}
}
Integer.MAX_VALUE表示int数据类型的最大取值数:2 147 483 647
Integer.MIN_VALUE表示int数据类型的最小取值数:-2 147 483 648
或者
class Solution {public int minDepth(TreeNode root) {if(root==null)return 0;if(root.left==null&&root.right==null)return 1;int left_depth=0,right_depth=0;if(root.left!=null)left_depth=minDepth(root.left);if(root.right!=null)right_depth=minDepth(root.right);if((root.left!=null&&left_depth <= right_depth)||root.right == null)return left_depth+1;else return right_depth+1;}
}
此法是根据不断与示例进行改进得到的,我们在平常练习中也可以多尝试自己书写代码,多尝试改动,以后面对这些问题就能迎刃而解了。
祝大家天天开心,心想事成!!!