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.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its minimum depth = 2.
思路
1.如果根为空的话,返回0就可以了
2.如果左子树和右子树都不为空的话,返回最小深度
3.如果左子树或者右子树为空的话,那么就返回不为空的子树的深度
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int minDepth(struct TreeNode* root) {
if(!root) return 0;
int left = minDepth(root->left);
int right = minDepth(root->right);
if(root->left && root->right) return left < right ? left + 1 : right + 1;
else return left + right + 1;
}