Welcome 歡迎光臨! 愛上網路 - 原本退步是向前

最大二元樹 LeetCode 654

給予一數值陣列, 找到其最大值作為根, 其左邊最大值作為左節點, 右邊最大值作為右節點,

再以左右節點的左右找出剩下的最大值作為下一層左右節點, 以此類推, 將所有數值轉為二元樹

Example 1:

Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree:

       6
    /    \
   3      5
    \     / 
     2   0   
       \
        1

 

class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
    def insertLeft(self,node):
        if not self.left:
            self.left=TreeNode(node)
        else:
            self.left.insertLeft(node)
    def insertRight(self,node):
        if not self.right:
            self.right=TreeNode(node)
        else:
            self.right.insertRight(node)
    def printTree(self):
        root=self
        stack=[root]
        res=[]
        while stack:
            root=stack.pop(0)
            res.append(root.val)
            if root.left:
                stack.append(root.left)
            if root.right:
                stack.append(root.right)
        print(res)

class Solution(object):
    def constructMaximumBinaryTree(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        #step1: root為nums中最大值
        #step2: 左子樹為 root在原nums中左邊部分遞歸構成
        #step3: 右子樹為 root在原nums中右邊部分遞歸構成
        if not nums:
            return None
        maxNum=max(nums) #找最大值
        pos=nums.index(maxNum) #找最大值在nums的位置
        root=TreeNode(maxNum) #建立新TreeNode
        root.left=self.constructMaximumBinaryTree(nums[:pos])
        root.right=self.constructMaximumBinaryTree(nums[pos+1:])
        return root

result=Solution()
nums = [3,2,1,6,0,5]
ans=result.constructMaximumBinaryTree(nums)
ans.printTree()

 

https://hackmd.io/@Hungen/BkN4zGsYo?utm_source=preview-mode&utm_medium=rec

 

======================

# 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 constructMaximumBinaryTree(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        if len(nums) <= 0:
            return None
        root_index = nums.index(max(nums))
        left_nums = nums[:root_index]
        right_nums = nums[root_index + 1:]
        root = TreeNode(max(nums))
        root.left = self.constructMaximumBinaryTree(left_nums)
        root.right = self.constructMaximumBinaryTree(right_nums)
        return root

 

 

https://gist.github.com/ryuji0123/413a20145dac3c9abdf0926d44cbc089

[ Python ] 瀏覽次數 : 42 更新日期 : 2024/07/29