题目
leetCode 第 111 题,二叉树的最小深度 关联类型:树
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:2
示例 2:
输入:root = [2,null,3,null,4,null,5,null,6]
输出:5
做题时间
/**
* 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) {
}
}
以上给出方法输入参数,完成作答。
题目分析
- 题目是找一个二叉树的最小深度,是指根节点到叶子结点的最小距离
- 首先可以想到使用深度优先搜索的方法,遍历整棵树,记录最小深度。
- 对于每一个非叶子节点,我们只需要分别计算其左右子树的最小叶子节点深度。这样就将一个大问题转化为了小问题,可以递归地解决该问题。
解答分析
本文只分析本人做题思路,仅供参考,了解一种解题思想,其他各种做题思路请上网查阅。
解答成功:
执行耗时:10 ms,击败了13.00% 的Java用户
内存消耗:59.4 MB,击败了10% 的Java用户
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
} else {
return 1 + getMinDepth(root);
}
}
public int getMinDepth(TreeNode node) {
if (node.left == null && node.right == null) {//叶子节点
return 0;
} else if (node.left == null) {//左子树为空就返回右子树深度
return 1 + getMinDepth(node.right);
} else if (node.right == null) {//右子树为空就返回左子树深度
return 1 + getMinDepth(node.left);
} else {//返回左右最小叶子节点深度
return 1 + Math.min(getMinDepth(node.left), getMinDepth(node.right));
}
}
}