題目
給定一個(gè)不重復(fù)的整數(shù)數(shù)組 nums 。最大二叉樹可以用下面的算法從 nums 遞歸地構(gòu)建:
- 創(chuàng)建一個(gè)根節(jié)點(diǎn),其值為 nums 中的最大值。
- 遞歸地在最大值左邊的子數(shù)組前綴上構(gòu)建左子樹。
- 遞歸地在最大值右邊的子數(shù)組后綴上構(gòu)建右子樹。
返回 nums 構(gòu)建的最大二叉樹。
例:
輸入:nums = [3,2,1,6,0,5]
輸出:[6,3,5,null,2,0,null,null,1]
解釋:遞歸調(diào)用如下所示:
-
[3,2,1,6,0,5] 中的最大值是 6 ,左邊部分是 [3,2,1] ,右邊部分是 [0,5] 。
-
[3,2,1] 中的最大值是 3 ,左邊部分是 [] ,右邊部分是 [2,1] 。
- 空數(shù)組,無子節(jié)點(diǎn)。
-
[2,1] 中的最大值是 2 ,左邊部分是 [] ,右邊部分是 [1] 。
- 空數(shù)組,無子節(jié)點(diǎn)。
- 只有一個(gè)元素,所以子節(jié)點(diǎn)是一個(gè)值為 1 的節(jié)點(diǎn)。
-
[0,5] 中的最大值是 5 ,左邊部分是 [0] ,右邊部分是 [] 。
- 只有一個(gè)元素,所以子節(jié)點(diǎn)是一個(gè)值為 0 的節(jié)點(diǎn)。
-
空數(shù)組,無子節(jié)點(diǎn)。
-
[3,2,1] 中的最大值是 3 ,左邊部分是 [] ,右邊部分是 [2,1] 。
方法
思路同 105. 從前序與中序遍歷序列構(gòu)造二叉樹 和 106. 從中序與后序遍歷序列構(gòu)造二叉樹
- 判斷數(shù)組是否為空,即二叉樹是否為空
- 取數(shù)組中的最大值作為根節(jié)點(diǎn)的值,構(gòu)造根節(jié)點(diǎn)
- 找到根節(jié)點(diǎn)的值在數(shù)組 nums 中的索引值,通過該值將數(shù)組 nums 分成左右子樹兩個(gè)部分
- 不斷調(diào)用 constructMaximumBinaryTree 函數(shù),構(gòu)造二叉樹
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def constructMaximumBinaryTree(self, nums):
if not nums:
return None
root_val = max(nums)
root = TreeNode(root_val)
separator = nums.index(root_val)
left = nums[: separator]
right = nums[separator + 1:]
root.left = self.constructMaximumBinaryTree(left)
root.right = self.constructMaximumBinaryTree(right)
return root
