My JavaScript Solution


  • 0
    T

    The approach is pretty easy to figure out. Using recursive function to construct the tree like building the BST. Here is my solution:

    function findMaxIdx(nums, begin, end){
        let ret = begin;
        for(let i=begin+1; i<=end; i++){
            if(nums[ret] < nums[i]){
                ret = i;
            }
        }
        return ret;
    }
    
    function createMaxBinaryTree(nums, begin, end){
        if(begin > end){
            return null;
        }
        
        let maxIdx = findMaxIdx(nums, begin, end);
        let root = new TreeNode(nums[maxIdx]);
        root.left = createMaxBinaryTree(nums, begin, maxIdx-1);
        root.right = createMaxBinaryTree(nums, maxIdx+1, end);
        return root;
    }
    
    var constructMaximumBinaryTree = function(nums) {
        //special case
        if(!nums || nums.length === 0){
            return null;
        }
        return createMaxBinaryTree(nums, 0, nums.length-1);
    };
    
    

  • 0
    D

    Hi.
    Was this code accepted by leetcode ?
    I have issue with accepting my script.
    System somehow converts my response [6,3,5,null,2,0,null,null,1] to [6,3,5,[],2,0,[],[],1]
    Did you face same issue ?

    Thank you .


  • 0
    T
    This post is deleted!

  • 0
    T

    @deniscoder My code could pass the leetcode judgement. Let me check your testcase.


Log in to reply
 

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