您的位置:首页 > 编程语言 > C语言/C++

【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);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode