LeetCode maximum binary tree

 

# Definition for a binary tree node.

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


class Solution(object):
    def make_tree(self,root,nums,is_left):
        if len(nums)==0:return
        max_ind=nums.index(max(nums))
        if is_left:
            root.left=TreeNode(nums[max_ind])
            if len(nums[0:max_ind]) > 0:
                self.make_tree(root.left, nums[0:max_ind], True)
            if len(nums[max_ind + 1:]) > 0:
                self.make_tree(root.left, nums[max_ind + 1:], False)
        else:
            root.right=TreeNode(nums[max_ind])
            if len(nums[0:max_ind]) > 0:
                self.make_tree(root.right, nums[0:max_ind], True)
            if len(nums[max_ind + 1:]) > 0:
                self.make_tree(root.right, nums[max_ind + 1:], False)

    def constructMaximumBinaryTree(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        root=TreeNode(max(nums))
        max_ind=nums.index(max(nums))
        self.make_tree(root,nums[0:max_ind],True)
        self.make_tree(root,nums[max_ind+1:],False)
        return root

nums=[3,2,1,6,0,5]
sl=Solution()
root=sl.constructMaximumBinaryTree(nums)
print root

 

你可能感兴趣的:(数据结构与算法)