[LeetCode] Minimum Depth of Binary Tree
来源:互联网 发布:淘宝账号冻结怎么解冻 编辑:程序博客网 时间:2024/06/07 14:56
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.
问题描述:给定一个二叉树,找到它的最小深度。最小深度定义为从根节点到最近的叶子节点的最短路径。
看到这个题,一般人可能会写出下面的代码:
int minDepth(TreeNode *root) { if(root == NULL) return 0; int lh = minDepth(root->left); int rh = minDepth(root->right); return lh<rh ? lh+1 : rh+1; }不过仔细想想,这段代码求的是什么呢?这段代码求的是节点的最低高度。直观的解释是节点的高度是左右孩子节点的深度的最小值,那得到的应该是节点的最小高度值。
本题要求的是根节点到最近的叶子节点的最短路径。那么,就可以用一个变量来跟踪叶子节点的层次,不过当左子树或者右子树为空时,就必须分开讨论了。
class Solution {public: int minD(TreeNode *root, int lev) { if(root == NULL) return lev; if(root->left == NULL && root->right == NULL) return lev; if(root->left == NULL && root->right) return minD(root->right, lev + 1); if(root->left && root->right == NULL) return minD(root->left, lev + 1); int lh = minD(root->left, lev + 1); int rh = minD(root->right, lev + 1); return lh<rh ? lh : rh; } int minDepth(TreeNode *root) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(root == NULL) return 0; return minD(root, 1); }};
- LeetCode: Minimum Depth of Binary Tree
- [Leetcode] Minimum Depth of Binary Tree
- LeetCode : Minimum Depth of Binary Tree
- leetcode 31: Minimum Depth of Binary Tree
- [LeetCode] Minimum Depth of Binary Tree - BFS
- [LeetCode] Minimum Depth of Binary Tree - DFS
- 【leetcode】Minimum Depth of Binary Tree
- LeetCode:Minimum Depth of Binary Tree
- [LeetCode]Minimum Depth of Binary Tree
- [Leetcode]Minimum Depth of Binary Tree
- [leetcode]Minimum Depth of Binary Tree
- Leetcode: Minimum Depth of Binary Tree
- LeetCode-Minimum Depth of Binary Tree
- [leetcode] Minimum Depth of Binary Tree
- LeetCode - Minimum Depth of Binary Tree
- 【Leetcode】Minimum Depth of Binary Tree
- LeetCode | Minimum Depth of Binary Tree
- LeetCode - Minimum Depth of Binary Tree
- VS显示行号
- 插入排序算法
- 远程定损管理系统
- SqlServer中如何获取年月日
- Linux 高可用(HA)集群之Pacemaker详解
- [LeetCode] Minimum Depth of Binary Tree
- JMeter学习笔记
- Eclipse中openfire3.8.2源码部署及生成安装文件
- Python中subprocess模块的使用
- 汉诺塔的实现 递归
- 基于Libevent的流媒体转发程序 性能测试
- ForEach 的使用
- Android应用开发之Session,Cookie
- 简单分析一下socket中的bind