2021.2.10 刷题(构造最大二叉树)

题目链接:https://leetcode-cn.com/problems/maximum-binary-tree
题目描述:
给定一个不含重复元素的整数数组 nums 。一个以此数组直接递归构建的 最大二叉树 定义如下:
二叉树的根是数组 nums 中的最大元素。
左子树是通过数组中 最大值左边部分 递归构造出的最大二叉树。
右子树是通过数组中 最大值右边部分 递归构造出的最大二叉树。
返回有给定数组 nums 构建的 最大二叉树 。


题解:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* travle(vector<int>& nums, int left, int right)
    {
        if(left >= right) return nullptr;
        int maxIndex = left;
        int maxVal = nums[maxIndex];
        for(int i = left + 1; i < right; i++)
        {
            if(nums[i] > maxVal)
            {
                maxVal = nums[i];
                maxIndex = i;
            }
        }
        TreeNode* root = new TreeNode(maxVal);
        root->left = travle(nums, left, maxIndex);
        root->right = travle(nums, maxIndex + 1, right);
        return root;
    }
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
       if(nums.size() == 0)
            return nullptr;
        return travle(nums, 0, nums.size());
    }
};

posted @ 2021-02-10 16:24  张宵  阅读(83)  评论(0编辑  收藏  举报