当前位置:网站首页>小黑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

边栏推荐
- MySQL notes under
- WEB安全基础 - - -漏洞扫描器
- ELK deployment script---pro test available
- 分布式.幂等性
- 调度中心xxl-Job
- Error occurred while trying to proxy request The project suddenly can't get up
- 【愚公系列】2022年07月 Go教学课程 015-运算符之赋值运算符和关系运算符
- DOM系列之scroll系列
- WMware Tools installation failed segmentation fault solution
- 【Yugong Series】July 2022 Go Teaching Course 019-For Circular Structure
猜你喜欢
随机推荐
【Yugong Series】July 2022 Go Teaching Course 013-Constants, Pointers
ShardingSphere之水平分库实战(四)
【愚公系列】2022年07月 Go教学课程 013-常量、指针
typescript9 - common base types
typescript14-(单独指定参数和返回值的类型)
MySQL数据库进阶篇
什么是Promise?Promise的原理是什么?Promise怎么用?
图像处理工具设计
typescript16-void
BOM系列之history对象
typescript12 - union types
Error in go mode tidy go warning “all” matched no packages
go mode tidy出现报错go warning “all“ matched no packages
系统设计.短链系统设计
XSS related knowledge
MySql数据恢复方法个人总结
typescript17-函数可选参数
MySQL筑基篇之增删改查
【952. Calculate the maximum component size according to the common factor】
WEB Security Basics - - - Vulnerability Scanner

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







