当前位置:网站首页>小黑leetcode之旅:117. 填充每个节点的下一个右侧节点指针 II
小黑leetcode之旅:117. 填充每个节点的下一个右侧节点指针 II
2022-07-31 00:52:00 【小黑无敌】
层次遍历法
""" # Definition for a Node. class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next """
class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:
return root
# 层次遍历
q = deque([root])
while q:
n = len(q)
pre_node = None
for i in range(n):
node = q.popleft()
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
if i != 0:
pre_node.next = node
pre_node = node
return root

使用已建立的 next 指针
""" # Definition for a Node. class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next """
class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:
return root
# 生成孩子节点链表
def handle(node):
# 链表存在上一个节点
if self.last:
self.last.next = node
# 不存在上一个节点,则赋予nextStart
else:
self.nextStart = node
self.last = node
self.start = root
while self.start:
p = self.start
# 重制nextStart、last
self.nextStart = None
self.last = None
# 通过上一层链表生成孩子节点链表
while p:
if p.left:
handle(p.left)
if p.right:
handle(p.right)
p = p.next
# 下一个链表开始
self.start = self.nextStart
return root

边栏推荐
- The difference between h264 and h265 decoding
- The level of ShardingSphere depots in actual combat (4)
- GO GOPROXY代理设置
- ShardingSphere之未分片表配置实战(六)
- ROS2系列知识(3):环境配置
- typescript14-(单独指定参数和返回值的类型)
- GO GOPROXY proxy Settings
- IOT cross-platform component design scheme
- 【愚公系列】2022年07月 Go教学课程 016-运算符之逻辑运算符和其他运算符
- 24. 请你谈谈单例模式的优缺点,注意事项,使用场景
猜你喜欢

WEB安全基础 - - -漏洞扫描器

什么是Promise?Promise的原理是什么?Promise怎么用?

DOM系列之 offset 系列

MySQL master-slave replication and read-write separation script - pro test available

Regular expression password policy and regular backtracking mechanism bypass

MySQL的触发器

ShardingSphere read-write separation (8)
![[In-depth and easy-to-follow FPGA learning 13---------Test case design 1]](/img/1c/a88ba3b01d2e2302c26ed5f730b956.png)
[In-depth and easy-to-follow FPGA learning 13---------Test case design 1]

MySQL数据库面试题总结(2022最新版)

Rocky/GNU之Zabbix部署(3)
随机推荐
Sping.事务的传播特性
分布式.分布式锁
MySQL master-slave replication and read-write separation script - pro test available
【多线程】
【愚公系列】2022年07月 Go教学课程 015-运算符之赋值运算符和关系运算符
ELK部署脚本---亲测可用
xss bypass: prompt(1)
(5) fastai application
DOM系列之scroll系列
Responsive layout vs px/em/rem
typescript14-(单独指定参数和返回值的类型)
ShardingSphere之垂直分库分表实战(五)
In Google Cloud API gateway APISIX T2A and T2D performance test
论文理解:“Designing and training of a dual CNN for image denoising“
mysql索引失效的常见9种原因详解
Jmeter参数传递方式(token传递,接口关联等)
Error in go mode tidy go warning “all” matched no packages
WMware Tools installation failed segmentation fault solution
程序员工作三年攒多少钱合适?
unity2D横版游戏教程4-物品收集以及物理材质