8 lines C++ recursion


  • 0
    class Solution {
    public:
        TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
            return DFS(nums, 0, nums.size());
        }
        
        TreeNode* DFS(vector<int>& nums, int l, int r){
            if(l == r) return NULL;
            int maxPos = l;
            for(int i = l; i < r; i++) if(nums[i] > nums[maxPos]) maxPos = i;
            TreeNode* root = new TreeNode(nums[maxPos]);
            root->left = DFS(nums, l, maxPos);
            root->right = DFS(nums, maxPos + 1, r);
            return root;
        }
    };
    

Log in to reply
 

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