C++ Recursive for beginner


  • 0
    J
    class Solution {
    public:
        TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
            int len=nums.size();
            int left=0;
            int right=len-1;
            if(len==0)
                return NULL;
            TreeNode* node = help(nums, left, right);
            return node;
        }
        
        TreeNode* help(vector<int>& nums, int left, int right)
        {
            if(left>right)
                return NULL;
            int pivot=0;
            int val=findMax(nums, left, right, pivot);
            TreeNode* node=new TreeNode(val);
            node->left=help(nums, left, pivot-1);
            node->right=help(nums, pivot+1, right);
            return node;
        }
        
        int findMax(vector<int>& nums, int left, int right, int& pivot)
        {
            int ans=nums[left];
            pivot=left;
            for(int i=left+1; i<=right; i++)
            {
                if(ans<nums[i])
                {
                    ans=nums[i];
                    pivot=i;
                }
            }
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.