Leetcode problem solution-654. The largest binary tree

Topic link

Title description:

Given an integer array with no repeated elements. A maximum binary tree constructed from this array is defined as follows:

The root of the binary tree is the largest element in the array.
The left subtree is the largest binary tree constructed from the left part of the maximum value in the array.
The right subtree is the largest binary tree constructed from the right part of the maximum value in the array.
Construct the largest binary tree from the given array and output the root node of this tree.

Example:

Input: [3,2,1,6,0,5] Output: Return the root node of the following tree:


Problem-solving ideas

  After reading the requirements of the topic, I smelled a strong idea of ​​divide and conquer. I distinguish between the left and right subtree intervals through the maximum index, and divide and conquer to the end. In fact, it is not that tall. In fact, it is to apply the pre-order traversal framework to recursively build the tree, divide and conquer. Thoughts are left to recursion. We mainly focus on the operation of the current node, that is, find [left...right]the maximum value of nums in the middle, and then newcreate the node in one step.


Code

class Solution {
    
    
public:
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
    
    
        if(nums.size() == 0)
            return NULL;

        return helper(nums, 0, nums.size() - 1);
    }

private:
    TreeNode* helper(vector<int>& nums, int left, int right){
    
    
        if(left > right)
            return NULL;
        
        int index = getMaxIndex(nums, left, right);
        TreeNode* root = new TreeNode(nums[index]);

        root->left = helper(nums, left, index - 1);
        root->right = helper(nums, index + 1, right);
        return root;
    }

    int getMaxIndex(vector<int>& nums, int left, int right){
    
    
        int result = -1, index = -1;
        for(int i = left; i <= right; i++){
    
    
            if(nums[i] > result){
    
    
                result = nums[i];
                index = i;
            }
        }
        return index;
    }
};

If there are mistakes or not rigorous, please correct me, thank you very much.
My blog: http://breadhunter.gitee.io

Guess you like

Origin blog.csdn.net/weixin_40807714/article/details/105183477