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);
}
};