Python recursive solution


  • 0
    Y
        def constructMaximumBinaryTree(self, A):
            """
            :type A: List[int]
            :rtype: TreeNode
            """
            def getMax(A):
                n=len(A)
                idx=-1
                Maxv=-sys.maxint-1
                for i in xrange(n):
                    if Maxv<A[i]:
                        idx=i
                        Maxv=A[i]
                return (idx,Maxv)
    
            def buildT(A):
                if len(A)==0: return None
                idx,Maxv=getMax(A)
                Node=TreeNode(Maxv)
                Node.left=buildT(A[:idx])
                Node.right=buildT(A[idx+1:])
                return Node
            root=buildT(A)
            return root
    

Log in to reply
 

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