minimum-depth-of-binary-tree
2016-06-14 09:56
225 查看
1.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.
题目的意思是找出根节点到叶子节点最短的一条路径的深度,这个深度等于左子树与右子树中最小的深度+1,但需要考虑的是如果左子树或者右子树为空,那么这个深度就是不为空的子树深度+1。public class Solution {
public int run(TreeNode root) {
if(root==null) return 0;
else{
if(root.left==null&&root.right==null) return 1;//到达叶子节点
else{
int left_num=run(root.left)+1;
int right_num=run(root.right)+1;
if(left_num>right_num){
if(root.left==null||root.right==null) return left_num;
else return right_num;
}else{
if(root.left==null||root.right==null) return right_num;
else return left_num;
}
}
}
}
}
2.还有一个类型的题目,求二叉树从根节点到某个叶子节点路径的val值最小是多少。做法与上面一样。
private static int getlength(TreeNode tNode) {
if(tNode==null) return 0;
else{
int minLeft=getlength(tNode.leftNode)+tNode.value;
int minRight=getlength(tNode.rightNode)+tNode.value;
if(tNode.leftNode==null) return minRight;
if(tNode.rightNode==null) return minLeft;
if(minLeft<minRight) return minLeft;
else return minRight;
}
}
path from the root node down to the nearest leaf node.
题目的意思是找出根节点到叶子节点最短的一条路径的深度,这个深度等于左子树与右子树中最小的深度+1,但需要考虑的是如果左子树或者右子树为空,那么这个深度就是不为空的子树深度+1。public class Solution {
public int run(TreeNode root) {
if(root==null) return 0;
else{
if(root.left==null&&root.right==null) return 1;//到达叶子节点
else{
int left_num=run(root.left)+1;
int right_num=run(root.right)+1;
if(left_num>right_num){
if(root.left==null||root.right==null) return left_num;
else return right_num;
}else{
if(root.left==null||root.right==null) return right_num;
else return left_num;
}
}
}
}
}
2.还有一个类型的题目,求二叉树从根节点到某个叶子节点路径的val值最小是多少。做法与上面一样。
private static int getlength(TreeNode tNode) {
if(tNode==null) return 0;
else{
int minLeft=getlength(tNode.leftNode)+tNode.value;
int minRight=getlength(tNode.rightNode)+tNode.value;
if(tNode.leftNode==null) return minRight;
if(tNode.rightNode==null) return minLeft;
if(minLeft<minRight) return minLeft;
else return minRight;
}
}
相关文章推荐
- 创新不是解难题!
- Android webview使用详解
- Js函数声明与函数表达式的区别
- Resharper 8.2 注册码
- Oracle 分区表的新增、修改、删除、合并。普通表转分区表方法
- linux所有服务列表
- JVM远程监控实现方法
- 服务器站点崩溃的几种原因及解决方案
- Android悬浮窗实现 使用WindowManager
- NHbiernate 配置
- JAVA字符串转日期或日期转字符串
- tail 源码分析
- redis系列--服务级别命令
- Java各种设计模式
- 日期加减天数js
- oracle编译死锁问题解决
- 【linux】Cache和Buffer的区别
- Java回顾篇——单列的设计模式。
- 主机访问虚拟机oracle数据库
- Android 常用 adb 命令总结