Given a binary tree, to find out the minimum depth.
Minimum depth is the number of nodes in the shortest path from the root node to leaf nodes nearest.
Description: leaf node is a node has no child nodes.
Example:
Given binary tree [3,9,20, null, null, 15,7],
3
/ \
9 20
/ \
15 7
2 returns to its minimum depth.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int DFS(struct TreeNode* root)
{
if(!root)return 0;
int left=0,right=0;
if(root->left)left=DFS(root->left);
if(root->right)right=DFS(root->right);
if(left==0)return right+1;
else if(right==0)return left+1;
else return left<right?left+1:right+1;
}
int minDepth(struct TreeNode* root){
if(!root)return 0;
return DFS(root);
}
When execution: 16 ms, beat the 91.63% of all users in C submission
Memory consumption: 9.9 MB, defeated 100.00% of all users in C submission