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 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) {
int res = INT_MAX;
if(!root) return 0;
treeHeight(root, 1, res);
return res;
}
private:
void treeHeight(TreeNode* root, int height, int& minHeight){
if(!root->left && !root->right){
minHeight = min(height, minHeight);
return;
}
if(root->left) treeHeight(root->left, height+1, minHeight);
if(root->right) treeHeight(root->right, height+1, minHeight);
}
};