【Leetcode】654:最大二叉树

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
        if len(nums)==0:
            return None
        if nums==None:
            return None
        i=0
        max_numer=0
        while i<len(nums):
            if max_numer<nums[i]:
                max_numer=nums[i]
            i+=1
        # the index of the max numeber
        index=0
        while index<len(nums):
            if nums[index]==max_numer:
                break
            index+=1
        
        new_Node=TreeNode(max_numer)
        #记住Python永远是!左闭右开!!
        new_Node.left=self.constructMaximumBinaryTree(nums[0:index])
        new_Node.right=self.constructMaximumBinaryTree(nums[index+1:])
        return new_Node

这个题目总的来说只要读懂了题目,就能立马解答出来,不需要什么时间。记住python是左闭右开的就好

 

posted @ 2021-04-05 21:21  Geeksongs  阅读(38)  评论(0编辑  收藏  举报

Coded by Geeksongs on Linux

All rights reserved, no one is allowed to pirate or use the document for other purposes.