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.
Attention:
from root to leaf distance
1
2
3 5
4
this distance is till 3 not 1. should find the nearest leaf!!
My Code:
int minDepth(TreeNode *root) {
if(root == NULL) return 0;
else if(root->left == NULL && root->right == NULL)
return 1;
else if(root->left == NULL && root->right != NULL)
return 1 + minDepth(root->right);
else if(root->right == NULL && root->left != NULL)
return 1 + minDepth(root->left);
else
return 1 + std::min(minDepth(root->left), minDepth(root->right));
}
No comments:
Post a Comment