【Leetcode】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.

class Solution(object):

    def constructMaximumBinaryTree(self, nums):

        """

        :type nums: List[int]

        :rtype: TreeNode

        """

        if not nums:

            return None

        root = TreeNode(max(nums))

        maxIndex = nums.index(max(nums))

        root.left = self.constructMaximumBinaryTree(nums[:maxIndex])

        root.right = self.constructMaximumBinaryTree(nums[maxIndex+1:])

        return root

1 构建一个binary tree,分为3步,第一步建立root,第二步建立左子树,第二步建立右子树

2 下面的就再进行递归就ok了

3 还有一个关键点是找到max的position

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容