LeetCode 111. Minimum Depth of Binary Tree (二叉树最小的深度)
2017-07-04 05:28
429 查看
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
题目标题:Tree
这道题目给了我们一个二叉树,让我们找到它最小的深度,注意这里的最小深度是指root 到一个 leaf node。
举个例子: 1
/
2
/
3
这种情况,最小depth 是3, 而不是因为1的right 是null ,最小depth 就等于1了。
和求最大深度差不多,每次遇到null node 返回0。接着每一个点返回 left 和right 中小的那一个depth + 1。但是我们需要控制住一个情况,就是如果parent 的left 和right 其中有一个返回的是0, 意思是有一个null 点, 那么这里就不能取两个child 中小的那个了,因为一个点是null, 另一个不是,那么就说明,null点不是leaf 点。 这种情况只需要返回那个不是null 的点的 depth + 1 就可以了。
Java Solution:
Runtime beats 17.13%
完成日期:07/03/2017
关键词:Tree
关键点:设条件控制住left 和right 其中一个点是null 的这种情况,另外返回其他值
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int minDepth(TreeNode root) { if(root == null) return 0; int left_depth = minDepth(root.left); int right_depth = minDepth(root.right); if(left_depth == 0 && right_depth != 0) return right_depth + 1; else if(left_depth != 0 && right_depth == 0) return left_depth + 1; else return Math.min(left_depth, right_depth) + 1; } }
参考资料:N/A
LeetCode 算法题目列表 - LeetCode Algorithms Questions List
相关文章推荐
- [LeetCode] Minimum Depth of Binary Tree 二叉树的最小深度
- LeetCode:111_Minimum Depth of Binary Tree | 二叉树的最小深度 | Easy
- Leetcode 111. Minimum Depth of Binary Tree 二叉树最小深度
- LeetCode:minimum-depth-of-binary-tree(二叉树最小深度)
- Leetcode Minimum Depth of Binary Tree 二叉树最小深度
- 【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】
- [LeetCode]111. Minimum Depth of Binary Tree--二叉树的最小深度
- LeetCode 111. Minimum Depth of Binary Tree(二叉树最小深度)
- 【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】
- [Java代码] [Leetcode] Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度
- 【LeetCode】Minimum Depth Of Binary Tree二叉树的最小深度 - Easy
- [LeetCode] Minimum Depth of Binary Tree 二叉树最小深度
- [LeetCode] 111. Minimum Depth of Binary Tree 二叉树的最小深度
- [LeetCode-111] Minimum Depth of Binary Tree (二叉树最小深度)
- Minimum Depth of Binary Tree 求二叉树最小高度/深度@LeetCode
- 【leetcode】Minimum Depth of Binary Tree 二叉树的最小深度 (JAVA)
- [Leetcode] The minimum depth of binary tree二叉树的最小深度
- [LeetCode 111] - 二叉树的最小深度 (Minimum Depth of Binary Tree)
- LeetCode Minimum Depth of Binary Tree 最小深度二叉树
- leetcode_111. Minimum Depth of Binary Tree 二叉树的最小深度