【leetcode c++】111 Minimum Depth of Binary Tree
2015-07-31 23:23
525 查看
Minimum Depth of Binary Tree
Given a binary tree, find its minimumdepth.
The minimum depth is the number of nodesalong the shortest path from the root node down to the nearest leaf node.
之前做了一题叫最大深度,这题求一个最小深度,求最大深度的时候我没有刻意去区分当前节点是不是叶子节点,因为呢,不管是不是叶子节点,每个节点都有一个当前深度,只要找到最大深度就可以了,相当于是【找所有节点中的最大深度】。而这题呢,相当于是【找叶子节点深度中的最小一个】。所以我们在叶子节点的时候才会去做判断,其他节点则继续遍历。同样的,你也可以拿Maximum Depth of Binary Tree那题的代码来改改就OK了。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if(NULL == root) return 0;
int lv = 0;
int minLv = -1;
Lv(root, lv, minLv);
return minLv + 1;
}
void Lv(TreeNode* root, int lv, int& minLv) {
if(NULL == root) return;
if(!root->left && !root->right)
{
if(-1 == minLv || lv < minLv) minLv = lv;
}
Lv(root->left, lv + 1, minLv);
Lv(root->right, lv + 1, minLv);
}
};
Given a binary tree, find its minimumdepth.
The minimum depth is the number of nodesalong the shortest path from the root node down to the nearest leaf node.
之前做了一题叫最大深度,这题求一个最小深度,求最大深度的时候我没有刻意去区分当前节点是不是叶子节点,因为呢,不管是不是叶子节点,每个节点都有一个当前深度,只要找到最大深度就可以了,相当于是【找所有节点中的最大深度】。而这题呢,相当于是【找叶子节点深度中的最小一个】。所以我们在叶子节点的时候才会去做判断,其他节点则继续遍历。同样的,你也可以拿Maximum Depth of Binary Tree那题的代码来改改就OK了。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if(NULL == root) return 0;
int lv = 0;
int minLv = -1;
Lv(root, lv, minLv);
return minLv + 1;
}
void Lv(TreeNode* root, int lv, int& minLv) {
if(NULL == root) return;
if(!root->left && !root->right)
{
if(-1 == minLv || lv < minLv) minLv = lv;
}
Lv(root->left, lv + 1, minLv);
Lv(root->right, lv + 1, minLv);
}
};
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解