Largest binary tree

Maximum Binary Tree
The difference between this problem and 105 and 106 is that there is only one array,
but it can also be constructed because the root node is found to be the largest and then divided,
so there is no need for two arrays to determine the root node and then divide it as before.

class Solution {
    
    
public:
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
    
    
     return traversal(nums,0,nums.size());
    }
    TreeNode*traversal(vector<int>&nums,int left,int right)
    {
    
    
       // 左右区间如果没有数就返回空
        if(left>=right) return NULL;
       //找到分割点的坐标(最大值的坐标
        int maxvalueindex=left;
        for(int i=left+1;i<right;i++)
        {
    
    
            if(nums[i]>nums[maxvalueindex])
            {
    
    
               maxvalueindex=i;
            }

        }
        //构造二叉树
        TreeNode *root=new TreeNode(nums[maxvalueindex]);
        //在左边区间找最大的
        root->left=traversal(nums,left,maxvalueindex);
        //在右边区间找最大的
        root->right=traversal(nums,maxvalueindex+1,right);

      return root;
    }
};

Guess you like

Origin blog.csdn.net/qq_44808694/article/details/113101816