二叉树:最大二叉树,习惯导致的一个致命的错误

二叉树:最大二叉树,小小的问题也会致命

在这里插入图片描述
题目不难,但我犯了一个错误并且检查了半天才发现,特此记录下:
错误:

class Solution {
    
    
public:
    int maxIndex(vector<int>& nums, int left, int right)//找到数组的最大值
    {
    
         
        int maxValue = 0;
        int maxIndex = 0;
        for(int i = left; i < right; ++i)
        {
    
    
            if(nums[i] > maxValue)
            {
    
    
                maxValue = nums[i];
                maxIndex = i;
            }
        }
        return maxIndex;
    }
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
    
    
        if(nums.empty())
        return nullptr;

        return construct(nums, 0, nums.size());
    }
    TreeNode* construct(vector<int>& nums, int left, int right)
    {
    
    
        //退出条件
        if(left == right)
        {
    
    
            return nullptr;
        }
        //构造根节点
        int index = maxIndex(nums, left, right);
        TreeNode* node = new  TreeNode(nums[index]);
        //构造左子树
        node->left = construct(nums, left, index);
        //构造右子树        
        node->right = construct(nums, index + 1, right);
        return node;       
    }
};

错误就在这:

int maxValue = 0;
int maxIndex = 0;

数组元素值为零时,构造这个节点进入for循环时候不满足if条件,maxValue和maxIndex都没发生改变,导致maxIndex出错。

比较大小的时候喜欢设置为0,这是一个很不好的行为,吃一堑长一智。

正确:

int maxValue = nums[left];
int maxIndex = left;

猜你喜欢

转载自blog.csdn.net/cckluv/article/details/112847968
今日推荐