LeetCode 111 二叉树的最小深度 Java 递归
2019-06-09 17:01
591 查看
题目描述
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7
返回它的最小深度 2.
题目分析
- 这道题目还是用递归解决。
- 需要注意的是一个陷阱,拿一个例子说明:
3 \ 20 / \ 15 7
这棵树中,3没有左孩子,但是有右孩子。也就是说它不是一个叶子结点。这点在判定时需要注意。
代码
class Solution { public int minDepth(TreeNode root) { // 树为空 if (root == null) return 0; // 左/右子树为空 --- 陷阱,此时它只有有一个孩子,不是叶子节点。 if (root.left == null) return minDepth(root.right) + 1; if (root.right == null) return minDepth(root.left) + 1; // 找深度 int leftDepth = minDepth(root.left); int rightDepth = minDepth(root.right); return Math.min(leftDepth, rightDepth) + 1; } }
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】
- 【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】
- leetcode之二叉树类之二叉树深度系列-----104/111/110/108/109 二叉树最大/最小深度/AVL树的判断和由有序序列生成(牵扯分治相关,OJ105/106)
- [LeetCode 111] - 二叉树的最小深度 (Minimum Depth of Binary Tree)
- 利用python 完成leetcode111 二叉树的最小深度
- [Leetcode] 104. 二叉树的最大深度与111. 二叉树的最小深度 java
- 【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java
- LeetCode 111 二叉树的最小深度
- [Java代码] [Leetcode] Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度
- leetcode 111-二叉树最小深度
- LeetCode-111.二叉树的最小深度(相关话题:深度优先)
- [LeetCode-111] Minimum Depth of Binary Tree (二叉树最小深度)
- LeetCode:111_Minimum Depth of Binary Tree | 二叉树的最小深度 | Easy
- Leetcode 111 python 二叉树的最小深度
- 【leetcode Java】二叉树的递归遍历以及最大深度的求解(Java)
- 【leetcode】Minimum Depth of Binary Tree 二叉树的最小深度 (JAVA)
- LeetCode 111. Minimum Depth of Binary Tree(二叉树最小深度)
- leetcode解题之Maximum/Minimum Depth of Binary Tree Java版(树的最大、最小深度)
- 二叉树的深度(递归和非递归)---java实现
- leetcode_111. Minimum Depth of Binary Tree 二叉树的最小深度