Minimum Depth of Binary Tree
来源:互联网 发布:广州金针软件下载 编辑:程序博客网 时间:2024/05/30 05:07
每日一题;
今天做的还是二叉树,求二叉树最小深度,貌似没有什么难度,需要注意的就两点:
1、递归的出口条件,开始以为是叶子节点,结果报错,因为如果只有一个节点这样容易返回0;所以出口要考虑一个节点的情况;
2、递归的过程。
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 binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int minDepth(TreeNode root) { TreeNode treeNode = root; if(treeNode == null){ return 0; } if(treeNode.left==null && treeNode.right == null){ return 1; } if(treeNode.right == null){ return minDepth(treeNode.left)+1; } if(treeNode.left == null){ return minDepth(treeNode.right)+1; } int left = minDepth(treeNode.left); int right = minDepth(treeNode.right); return left<right?left+1:right+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
- POJ1979 红与黑 DFS
- 想成功,每天做一点折磨你的事——读书笔记(三)
- IMP-00010:不是有效的导出文件,头部验证失败
- 改善mysqli中使用DELETE的小bug
- 大数据的学习方向
- Minimum Depth of Binary Tree
- HUST 1017 Exact cover(DLX精确覆盖)
- iOS8 Core Location
- myeclipse部署时出现could not be redeployed because ……错误
- [android] 百度地图开发 (二).定位城市位置和城市POI搜索
- c语言中制表符的输出问题
- chrome 控制台console的用法(学了之后对于调试js可是大大有用的哦)
- iOS中的沙盒机制
- poj 2112 Optimal Milking(floyd+二分+最大流)