Minimum Depth of Binary Tree
来源:互联网 发布:保罗皮尔斯知乎 编辑:程序博客网 时间:2024/06/06 01:34
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.
这个题目的重点是如何处理最小值。应该将函数分为两部分一个是root == null 时返回0,判断不是叶子节点是返回一个极大值。
python
"""Definition of TreeNode:class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None"""class Solution: """ @param root: The root of binary tree. @return: An integer """ def minDepth(self, root): # write your code here if root is None: return 0 return self.getDepth(root) def getDepth(self, root): if root is None: return sys.maxint if root.left is None and root.right is None: return 1 left = self.getDepth(root.left) right = self.getDepth(root.right) return 1 + min(left, right)
java
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */public class Solution { /** * @param root: The root of binary tree. * @return: An integer. */ public int minDepth(TreeNode root) { // write your code here if (root == null) { return 0; } return getDepth(root); } private int getDepth(TreeNode root) { if (root == null) { return Integer.MAX_VALUE; } if (root.left == null && root.right == null) { return 1; } int left = getDepth(root.left); int right = getDepth(root.right); int depth = 1 + Math.min(left, right); return depth; }}
阅读全文
0 0
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Java8,静态默认方法,Lambd继承接口写法,与代码覆盖率测试
- r2uqqxkm
- 学习SpringMVC——整合Hibernate、Spring、SpringMVC
- 五种方式让你在java中读取properties文件内容不再是难题
- 洛谷P1312 Mayan游戏
- Minimum Depth of Binary Tree
- hadoop错误:Cannot create directory /opt/data/tmp/dfs/name/current
- windows下安装Scrapy步骤(支持Python3.X)
- Java并发编程艺术 7 Java的13个原子操作类
- Google Earth Engine(GEE)学习笔记 三
- Java多线程--死锁
- HDU4864Task(贪心)
- <c语言经典100例>c5 小到大排列
- 快速入门过程与方法:设计与思路;如何学习新的知识框架,建立思维模式,熟悉应用场景体系