【LeetCode111】Minimum Depth of Binary Tree

/**
 * 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->left == NULL)//左边是空,左边就没有意义了,不能0+1
            return minDepth(root->right)+1;
        if(root->right == NULL)
            return minDepth(root->left)+1;
        int left = minDepth(root->left);
        int right = minDepth(root->right);
        return min(left, right) + 1;
    }
};

空;左空;右空;都空

猜你喜欢

转载自blog.csdn.net/weixin_39458342/article/details/87901004