1. 程式人生 > 其它 >LeetCode | 0654. Maximum Binary Tree最大二叉樹【Python】

LeetCode | 0654. Maximum Binary Tree最大二叉樹【Python】

技術標籤:LeetCode個人題解# 二叉樹二叉樹leetcodepython演算法

Problem

LeetCode

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:

  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.

Construct the maximum tree by the given array and output the root node of this tree.

Example 1:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片儲存下來直接上傳(img-bTSB8rfA-1609944183381)(https://assets.leetcode.com/uploads/2020/12/24/tree1.jpg)]

Input: nums = [3,2,1,6,0,5]
Output: [6,3,5,null,2,0,null,null,1]

Example 2:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片儲存下來直接上傳(img-w7UzhSQ2-1609944183394)(https://assets.leetcode.com/uploads/2020/12/24/tree2.jpg)]

Input: nums = [3,2,1]
Output: [3,null,2,null,1]

Constraints:

  • 1 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000
  • All integers in nums
    are unique.

問題

力扣

給定一個不含重複元素的整數陣列 nums 。一個以此陣列直接遞迴構建的 最大二叉樹 定義如下:

  1. 二叉樹的根是陣列 nums 中的最大元素。
  2. 左子樹是通過陣列中 最大值左邊部分 遞迴構造出的最大二叉樹。
  3. 右子樹是通過陣列中 最大值右邊部分 遞迴構造出的最大二叉樹。

返回有給定陣列 nums 構建的 最大二叉樹

示例 1:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片儲存下來直接上傳(img-3pLMglok-1609944183402)(https://assets.leetcode.com/uploads/2020/12/24/tree1.jpg)]

輸入:nums = [3,2,1,6,0,5]
輸出:[6,3,5,null,2,0,null,null,1]
解釋:遞迴呼叫如下所示:
- [3,2,1,6,0,5] 中的最大值是 6 ,左邊部分是 [3,2,1] ,右邊部分是 [0,5] 。
  - [3,2,1] 中的最大值是 3 ,左邊部分是 [] ,右邊部分是 [2,1] 。
    - 空陣列,無子節點。
    - [2,1] 中的最大值是 2 ,左邊部分是 [] ,右邊部分是 [1] 。
      - 空陣列,無子節點。
      - 只有一個元素,所以子節點是一個值為 1 的節點。
  - [0,5] 中的最大值是 5 ,左邊部分是 [0] ,右邊部分是 [] 。
    - 只有一個元素,所以子節點是一個值為 0 的節點。
    - 空陣列,無子節點。

示例 2:

img

輸入:nums = [3,2,1]
輸出:[3,null,2,null,1]

提示:

  • 1 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000
  • nums 中的所有整數 互不相同

思路

遞迴

1. 遍歷找到陣列最大值和對應索引
2. 分別對最大值左右兩邊陣列進行遞迴呼叫,構造左右子樹

Python3 程式碼

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
        # 特判
        if not nums:
            return None
        
        # 找到陣列中的最大值和對應的索引
        maxVal = max(nums)
        maxIndex = nums.index(maxVal)
 
        root = TreeNode(nums[maxIndex])
        # 遞迴構造左右子樹
        root.left = self.constructMaximumBinaryTree(nums[:maxIndex])
        root.right = self.constructMaximumBinaryTree(nums[maxIndex + 1:])
        
        return root

GitHub 連結