LeetCode maximum binary tree

Posted zbxzc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

 

以上是关于LeetCode maximum binary tree的主要内容,如果未能解决你的问题,请参考以下文章

[Lintcode]97. Maximum Depth of Binary Tree/[Leetcode]104. Maximum Depth of Binary Tree

[Leetcode] Maximum Depth of Binary Tree

[LeetCode]题解(python):104 Maximum Depth of Binary Tree

[LeetCode] Maximum Binary Tree

LeetCode 104. Maximum Depth of Binary Tree

leetcode:Maximum Depth of Binary Tree