小黑代码
# 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]:
def dfs(start, end):
# 递归推出条件
if start > end:
return
# 获取最大值和最大值对应索引
index = -1
max_ = -1
for i in range(start, end+1):
if nums[i] > max_:
max_ = nums[i]
index = i
node = TreeNode(val=max_)
node.left = dfs(start, index-1)
node.right = dfs(index+1, end)
return node
return dfs(0, len(nums)-1)
单调栈法
# 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]:
n = len(nums)
# 找到左右的“一大”
left = [-1] * n
right = [-1] * n
nodes = []
# 初始化单调栈
q = []
for i in range(n):
# 将该结点插入数组
node = TreeNode(val=nums[i])
nodes.append(node)
# 满足单调栈出栈条件
while q and nums[q[-1]] < nums[i]:
top = q.pop()
right[top] = i
# 栈非空的话,赋予该元素左“一大”
if q:
left[i] = q[-1]
q.append(i)
# 通过左右"一大"进行构建二叉树
print(right,left)
root = None
for i in range(n):
# 根结点
if left[i] == right[i] == -1:
root = nodes[i]
# 向右一大看齐
elif left[i] == -1 or (right[i] != -1 and nums[left[i]] > nums[right[i]]):
nodes[right[i]].left = nodes[i]
else:
nodes[left[i]].right = nodes[i]
return root
优先栈改进
# 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]:
nodes = []
n = len(nums)
# 初始化优先栈
q = []
for i in range(n):
node = TreeNode(val=nums[i])
# 优先栈工作
while q and nums[i] > nums[q[-1]]:
node.left = nodes[q[-1]]
q.pop()
if q:
nodes[q[-1]].right = node
q.append(i)
nodes.append(node)
return nodes[q[0]]
小黑生活
完成了销售的测评,并且通过了面试,但是思考好久小黑还是想前期先进军互联网
喜茶店的学习和面试,第一场校招面试把我鸽了,参加了第二场初创公司的实习面试,面试到七点。
飞速去找大黑驴共进晚餐
在齐齐哈尔烧烤店见面啦
喜提阴性
实习两次面试通过啦
去搓澡啦
回家自己涮个锅子啦
在学钢琴的地方望向东三环
事业单位考试,考前喝杯喜茶啦
晚上和一起秋招奇安信的小伙伴吃饭啦,恭喜他成功上岸(不愧是北理工硕士,学历高就是机会多啦),聊的非常开心
晚上回去直接去学钢琴啦
身边的人开始第二次阳了
晚上从钢琴教室出发,跑向国际贸易中心
重新收拾了一下屋子
早饭开始煎牛排啦
下午又来国贸学习啦,今天去蓝蛙~