#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 16 12:54:56 2018

@author: yanglinxuan
"""

#654	Maximum Binary Tree    

'''
Given an integer array with no duplicates. 
A maximum tree building on this array is defined as follow:

The root is the maximum number in the array.
The left subtree is the maximum tree constructed from left part 
subarray divided by the maximum number.
The right subtree is the maximum tree constructed from right part 
subarray divided by the maximum number.
Construct the maximum tree by the given array and output the root 
node of this tree.
'''
from random import randint
def randlist(n):
    l=[]
    for i in range(n):
        l.append(randint(0,100))
    return l



class TreeNode():
    def __init__(self,key):
        self.left=None
        self.right=None
        self.val=key
        


def constructbinarytree(nums):
    '''
    :type nums:list[int]
    :rtype:TreeNode
    '''
    def getssubtree(nums,start,end):
        if start==end:
            return None
        max_=max(nums[start:end])
        #create a tree called node with root max_
        node=TreeNode(max_)
        node.left=getssubtree(nums,start,nums.index(max_))
        node.right=getssubtree(nums,nums.index(max_)+1,end)
        return node
    
    return getssubtree(nums,0,len(nums))

nums=randlist(10)
constructbinarytree(nums)
    