leetcode | Minimum Depth of Binary Tree
来源:互联网 发布:美妆软件哪个好 编辑:程序博客网 时间:2024/05/01 20:17
rMinimum Depth of Binary Tree : https://leetcode.com/problems/minimum-depth-of-binary-tree/
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,
最短路径(最小深度)则是选择左右子树中深度小的加 1。
需要注意的是,空节点不算叶节点,所以遇到空节点子树时,需要返回另一颗子树的深度加 1;在求树的深度时,选的是深度较大的一个,故不需考虑空节点子树。
如:[1 2 NULL] 返回 2
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ //定义:NULL不是叶节点class Solution {public: int minDepth(TreeNode* root) { if (root == NULL) return 0; if (root->left == NULL) // 左子树没有叶节点 return minDepth(root->right)+1; if (root->right == NULL) // 右子树没有叶节点 return minDepth(root->left)+1; return min(minDepth(root->left), minDepth(root->right)) + 1; }};
0 0
- 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
- socket常用函数解析(1)
- jquery.flexslider.js带左右箭头且带按钮可滚动的图片插件
- android TextAppearanceSpan 使用注意事项。
- 黑马程序员---泛型,Collections,Arrays
- 如何中断一个正在运行的线程
- leetcode | Minimum Depth of Binary Tree
- NSOperationQueue和GCD的区别,以及在什么场合下使用
- 校验码
- 有道词典
- 调用有道词典查词
- 安装打印机时出现"无法安装,打印处理器不存在"
- 最大子向量和(连续子数组的最大和_1372
- 手游接入Facebook的那些坑
- 解读HTTP的META标签