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.
Subscribe to see which companies asked this question
/**
* 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 minlevel = 0;
int minDepth(TreeNode* root) {
if(!root)
return 0;
if(!root->left && !root->right)
return 1;
int leftdepth = minDepth(root->left);
int rightdepth = minDepth(root->right);
if(leftdepth == 0)
return rightdepth+1;
if(rightdepth == 0)
return leftdepth+1;
return min(leftdepth,rightdepth)+1;
}
};