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) {
if(!root) return 0;
int a=minDepth(root->left);
int b=minDepth(root->right);
if((a==0 && b!=0) || (a!=0 && b==0)) return max(a,b)+1; //不能min
return min(a,b)+1;
}
};