654. 最大二叉树
为保证权益,题目请参考 654. 最大二叉树(From LeetCode).
解决方案1
Python
python
# 654. 最大二叉树
# https://leetcode.cn/problems/maximum-binary-tree/
from typing import List, Optional, Dict
# 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]) -> Optional[TreeNode]:
# if len(nums) == 0:
# return None
# m = nums.index(max(nums))
# return TreeNode(
# val=nums[m],
# left=self.constructMaximumBinaryTree(nums[:m]),
# right=self.constructMaximumBinaryTree(nums[m + 1 :]),
# )
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
s = []
t: Dict[int, TreeNode] = dict()
for num in nums:
t[num] = TreeNode(val=num)
l = -1
while len(s) > 0 and num > s[-1]:
p = s.pop()
if l != -1:
t[p].right = t[l]
l = p
if l != -1:
t[num].left = t[l]
s.append(num)
l = -1
while len(s) > 0:
p = s.pop()
if l != -1:
t[p].right = t[l]
l = p
return t[l]
if __name__ == "__main__":
so = Solution()
t = so.constructMaximumBinaryTree([3, 2, 1, 6, 0, 5])
print(t)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61