Simple JavaScript Solution


  • 0
    R
    var constructMaximumBinaryTree = function(nums) {
        const maxNum = Math.max(...nums);
        const maxNumIndex = nums.indexOf(maxNum);
    
        const tree = new TreeNode(maxNum);
        const leftNums = nums.slice(0, maxNumIndex);
        const rightNums = nums.slice(maxNumIndex + 1, nums.length);
    
        if (leftNums.length > 0) {
            tree.left = constructMaximumBinaryTree(leftNums);
        }
    
        if (rightNums.length > 0) {
            tree.right = constructMaximumBinaryTree(rightNums);
        }
    
        return tree;
    };
    

Log in to reply
 

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