问题描述
代码
/**
* 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==NULL) return 0;
if(root->right==NULL &&root->left==NULL) return 1;
if(root->left==NULL &&root->right!=NULL) return minDepth(root->right)+1;
if(root->left!=NULL &&root->right==NULL) return minDepth(root->left)+1;
return min(minDepth(root->left),minDepth(root->right))+1;
}
};
为什么要根据左右孩子是否为空来决定返回的结果
比如测试样例【1,2】,我们借结果应当返回的是2,而不是1,就必须就左右孩子进行讨论