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.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void minDepthInternal(TreeNode *root, std::vector<TreeNode *> &treeVector, int &minDepth)
{
if (!root)
return;
treeVector.push_back(root);
if (root->left == NULL && root->right == NULL)
{
if (treeVector.size() < minDepth)
{
minDepth = treeVector.size();
}
treeVector.pop_back();
return;
}
minDepthInternal(root->left, treeVector, minDepth);
minDepthInternal(root->right, treeVector, minDepth);
treeVector.pop_back();
}
int minDepth(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!root)
return 0;
vector<TreeNode *> treeVector;
int minDepth = 10000;
minDepthInternal(root, treeVector, minDepth);
return minDepth;
}
};