654. Maximum Binary Tree - LeetCode

654. Maximum Binary Tree - LeetCode


Given a non-repeating array of integers  numsA maximum binary tree  can be constructed recursively using the following algorithm  nums:

  1. Create a root node whose value is  numsthe maximum value of .
  2. Recursively   builds the left subtree on the subarray prefix to the left  of  the maximum value.
  3. Recursively  builds the right subtree on the subarray suffix to the right of  the maximum value.

Returns  numsthe constructed _ ** maximum binary tree_**.

Example 1:

输入:nums = [3,2,1,6,0,5]
输出:[6,3,5,null,2,0,null,null,1]
解释:递归调用如下所示:
- [3,2,1,6,0,5] 中的最大值是 6 ,左边部分是 [3,2,1] ,右边部分是 [0,5] 。
    - [3,2,1] 中的最大值是 3 ,左边部分是 [] ,右边部分是 [2,1] 。
        - 空数组,无子节点。
        - [2,1] 中的最大值是 2 ,左边部分是 [] ,右边部分是 [1] 。
            - 空数组,无子节点。
            - 只有一个元素,所以子节点是一个值为 1 的节点。
    - [0,5] 中的最大值是 5 ,左边部分是 [0] ,右边部分是 [] 。
        - 只有一个元素,所以子节点是一个值为 0 的节点。
        - 空数组,无子节点。

Example 2:

输入:nums = [3,2,1]
输出:[3,null,2,null,1]

hint:

  • 1 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000
  • numsAll integers in are different from each other

  • updated in 2022-08-20 14:08
class Solution {
    
    
public:
    TreeNode* help(vector<int>& nums, int l, int r){
    
    
        if(l>r) return nullptr;
        if(l==r) return new TreeNode(nums[l]);
        int idx = max_element(nums.begin()+l, nums.begin()+r+1) - nums.begin();
        TreeNode* node = new TreeNode(nums[idx]);
        node->left = help(nums, l, idx-1);
        node->right = help(nums, idx+1, r);
        return node;
    }
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
    
    
        return help(nums, 0, nums.size()-1);
    }
};

Guess you like

Origin blog.csdn.net/aiyolo/article/details/126439561