Clean Ruby Solution


  • 0
    R
    def construct_maximum_binary_tree(nums)
        if nums.length == 1 
            return TreeNode.new(nums.first)
        end
        
        max, max_index = nums.each_with_index.max
        left_array = nums[0...max_index]
        right_array = nums[max_index+1...nums.length]
        
        node = TreeNode.new(max)
        
        node.left = construct_maximum_binary_tree(left_array) if !left_array.empty?
        node.right = construct_maximum_binary_tree(right_array) if !right_array.empty?
        
        node
    end
    

Log in to reply
 

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