Python using sort


  • 0
    D
        def constructMaximumBinaryTree(self, nums):
            idx = {x:i for i,x in enumerate(nums)}
            def insert(parent, child):
                if idx[child.val] > idx[parent.val]:
                    if parent.right:
                        insert(parent.right, child)
                    else:
                        parent.right = child
                else:
                    if parent.left:
                        insert(parent.left, child)
                    else:
                        parent.left = child
            nums.sort()
            root = TreeNode(nums.pop())
            while nums:
                insert(root, TreeNode(nums.pop()))
            return root

Log in to reply
 

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