111. Minimum Depth of Binary Tree
来源:互联网 发布:防水js是什么 编辑:程序博客网 时间:2024/06/04 19:14
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.
这里用递归解法,分了5种返回情况,详见代码,代码如下:/** * 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; } if (root.left == null && root.right == null) { return 1; } if (root.left == null && root.right != null) { return minDepth(root.right) + 1; } if (root.left != null && root.right == null) { return minDepth(root.left) + 1; } return Math.min(minDepth(root.left), minDepth(root.right)) + 1; }}也可以分别计算left和right,如果其中一方为0,返回left+right+1,如果都不为0,返回较小值+1,代码如下:
public class Solution { public int minDepth(TreeNode root) { if(root == null) return 0; int left = minDepth(root.left); int right = minDepth(root.right); return (left == 0 || right == 0) ? left + right + 1: Math.min(left,right) + 1; }}
0 0
- LeetCode 111. Minimum Depth of Binary Tree
- [LeetCode]111.Minimum Depth of Binary Tree
- 【LeetCode】111.Minimum Depth of Binary Tree
- [Leetcode] 111. Minimum Depth of Binary Tree
- 111.Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- [leetcode] 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree LeetCode
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 【LeetCode】111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- LeetCode *** 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- python3 小知识点
- leetcode 63. Unique Paths II
- MySQL重要概念图解(重要)
- notes Windows Batch Scripting wiki
- Phabricator
- 111. Minimum Depth of Binary Tree
- 数据结构实验之求二叉树后序遍历和层次遍历
- spring boot(一):入门篇
- MongoDB3.2磁盘碎片整理---compact详述
- 数据结构实验之二叉树三:统计叶子数
- 携程基于Storm的实时大数据平台实践
- 通带纹波,阻带衰减
- 【LeetCode】500. Keyboard Row
- mysql解决脏读、不可重复读、虚读的办法