Minimum Depth of Binary Tree
来源:互联网 发布:sql语句update语句 编辑:程序博客网 时间:2024/06/05 17:33
题目描述:
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.
分析:
题目让求的是从根节点到叶子节点的最"矮"树高度,可采用递归。递归计算的时候需要注意判断左子树或者右子树是否存在,当存在才进行递归计算。
代码:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */class Solution { public int minDepth(TreeNode root) { if (root == null) { return 0; } if (root.left == null && root.right == null) { // 叶子节点 return 1; } int min = Integer.MAX_VALUE; if (root.left != null) { min = minDepth(root.left); } if (root.right != null) { int minRight = minDepth(root.right); min = min < minRight ? min : minRight; } return min + 1; }}
阅读全文
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
- android media库中external的读取
- jsp之有标签体的标签、带参数的标签
- 15.5 Content-Encoding:内容编码
- 前端调用后台接口的几种方式
- boost和c++11创建线程的区别
- Minimum Depth of Binary Tree
- proteus 数码管动态显示问题解决
- 靶面尺寸和镜头焦距配套对应的视场角
- image宽高一致自适应
- 身价突破800亿美元的巴菲特却对比特币不屑一顾,说....
- windows可以ping通linux虚拟机的ip,但是ping不通主机名称
- QT 信号与槽
- JAVA性能调优
- Linux编译内核