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. 每进入一层用一个变量(这里是levelNum)记录当前从根节点到这一层节点的节点数
2. 当到达叶子节点的时候,就记录当前最小深度overall
2. 当所有的叶子节点都到达一遍之后,就得到了最终最小深度overall。
class Solution {
public:
int minDepth(TreeNode *root) {
if(root == nullptr) return 0;
int overall = INT_MAX;
int levelNum = 0;
minD(root, overall, levelNum);
return overall;
}
void minD(TreeNode *node, int &overall, int levelNum)
{
if(node == nullptr) return;
levelNum++;
minD(node->left, overall, levelNum);
minD(node->right, overall, levelNum);
if(node->left==nullptr && node->right==nullptr)
overall = min(overall,levelNum);
}
};
//2014-2-16 update
int minDepth(TreeNode *root)
{
if (!root) return 0;
if (!root->left && !root->right) return 1;
int L = root->left? minDepth(root->left)+1:INT_MAX;
int R = root->right? minDepth(root->right)+1:INT_MAX;
return min(L, R);
}