57. Minimum Depth of Binary Tree
来源:互联网 发布:2k16捏脸数据科比 编辑:程序博客网 时间:2024/06/06 06:58
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,2]这种,根节点缺少右子树的情况,则此时需要返回左子树的最小深度+1;如果根节点有两个孩子节点或者是没有孩子节点时则返回两个子树中较大者+1;如果根节点是空,则返回0
/** * 采用递归的思想做。当遇到类似于[1,2]这种,根节点缺少右子树的情况,则此时需要返回左子树的最小深度+1; * 如果根节点有两个孩子节点或者是没有孩子节点时则返回两个子树中较大者+1;如果根节点是空,则返回0 */public int minDepth(TreeNode root) {if(root == null){ return 0; }else{ int ll = minDepth(root.left); int rl = minDepth(root.right); /*如果根节点只有一个孩子,则返回有孩子的那个深度+1,防止求出的结果不是根节点到叶子节点的深度*/ if(ll*rl == 0 && ll+rl!=0){ return Math.max(ll,rl)+1; }else{/*其他情况就返回两个子树中深度较小的那个+1*/ return Math.min(ll, rl)+1; } } }
0 0
- 57. 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
- nil、Nil、NULL、NSNull的区别
- Scala单例对象
- shiro安全
- MySQL下添加用户以及给予权限的实现
- shiro内置过滤器详解
- 57. Minimum Depth of Binary Tree
- 底部导航栏FragmentTabHost
- CentOS常见问题记录
- 【Leetcode】219. Contains Duplicate II
- Crash Report 之移植PLCrashReporter到自己的app
- 二Java设计模式——工厂模式
- windows下并发I/O服务器模型对比(三)
- Spring +redis 集成 16进制问题 \xE7\x9C\x81t\x00\x0323e
- IIS系列:二、修改默认站点配置