LintCode:二叉树的最小深度
来源:互联网 发布:日本人的交友软件 编辑:程序博客网 时间:2024/06/05 23:46
Lintcode : 二叉树的最小深度
给定一个二叉树,找出其最小深度。
二叉树的最小深度为根节点到最近叶子节点的距离。
与二叉树的最大深度不同,不能单纯地使用递归,因为二叉树的深度必须是根结点到叶子结点的距离,不能单纯的比较左右子树的递归结果返回较小值,因为对于有单个孩子为空的节点,为空的孩子会返回0,但这个节点并非叶子节点,故返回的结果是错误的。
因此,当发现当前处理的节点有单个孩子是空时,返回一个极大值INT_MAX,防止其干扰结果。
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution {public: /** * @param root: The root of binary tree. * @return: An integer */ int minDepth(TreeNode *root) { // write your code here if (root == NULL) return 0; if (root->left == NULL && root->right == NULL) return 1; int m = minDepth(root->left) + 1; int n = minDepth(root->right) + 1; m = (m == 1 ? INT_MAX : m); n = (n == 1 ? INT_MAX : n); return m < n ? m : n ; }};
参考资料
0 0
- LintCode 二叉树的最小深度
- lintcode-二叉树的最小深度-155
- LintCode:二叉树的最小深度
- lintcode ----二叉树的最小深度
- Lintcode 二叉树的最小深度
- LintCode-二叉树的最小深度
- lintcode 二叉树的最小深度
- LintCode 二叉树的最小深度
- 二叉树的最小深度-LintCode
- lintcode 二叉树的最小深度
- LintCode 二叉树的最小深度
- lintcode 155 二叉树的最小深度
- LintCode 155-二叉树的最小深度
- 二叉树的最小深度-LintCode
- lintcode二叉树的最小深度
- lintcode——二叉树的最小深度
- lintcode(E) 二叉树最小深度
- lintcode minimum-depth-of-binary-tree 二叉树最小深度
- 学习爬虫的记录
- android--(BroadcastReceiver)
- 十二、机器学习系统设计笔记之大数据
- 欢迎使用CSDN-markdown编辑器
- 批处理文件 bat 的入门命令
- LintCode:二叉树的最小深度
- POJ-2028
- Brackets(区间DP)
- Repo和Git 版本管理常用命令
- [sicily]1150. 简单魔板
- linux 获取 CPU 使用信息
- 绘制虚线
- Mysql的下载和安装
- poj 1873 final 水题 位枚举凸包