【LeetCode】Maximum Binary Tree 最大值二叉树

Maximum Binary Tree 最大值二叉树

题意

  1. The root is the maximum number in the array.
  2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
  3. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.

解法

dfs

class Solution(object):
    def constructMaximumBinaryTree(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        if not nums:
            return None
        root = TreeNode(max(nums))
        idx = nums.index(root.val)
        root.left = self.constructMaximumBinaryTree(nums[:idx])
        root.right = self.constructMaximumBinaryTree(nums[idx+1:])
        return root

还有一种循环的写法,通过判断大小来确定是在左边还是右边。

class Solution(object):
    def constructMaximumBinaryTree(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        if not nums:
            return None
        node_stack = []
        for num in nums:
            node = TreeNode(num)
            # 判断当前值是否比之前的值大,大则放置在左边,小则放置在右边
            while node_stack and node.val > node_stack[-1].val:
                node.left = node_stack.pop()
            if node_stack:
                node_stack[-1].right = node
            node_stack.append(node)
        return node_stack[0]  # 最后剩下的一定是最大的值,也就是跟节点
posted @ 2017-10-08 08:02  banananana  阅读(225)  评论(0编辑  收藏  举报