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

边栏推荐
- Sping.事务的传播特性
- WMware Tools安装失败segmentation fault解决方法
- ShardingSphere之未分片表配置实战(六)
- Basic usage of async functions and await expressions in ES6
- Niuke.com question brushing training (4)
- mysql主从复制及读写分离脚本-亲测可用
- MySQL table design for message queue to store message data
- 查看zabbix-release-5.0-1.el8.noarch.rpm包内容
- Mysql systemized JOIN operation example analysis
- MySQL master-slave replication and read-write separation script - pro test available
猜你喜欢
随机推荐
Typescript14 - (type) of the specified parameters and return values alone
ABC 261 F - Sorting Color Balls (reverse pair)
xss bypass: prompt(1)
WMware Tools installation failed segmentation fault solution
Consistency and Consensus of Distributed Systems (1) - Overview
WEB Security Basics - - - Vulnerability Scanner
论文理解:“Designing and training of a dual CNN for image denoising“
ShardingSphere之水平分库实战(四)
C语言力扣第48题之旋转图像。辅助数组
Can deep learning solve the parameters of a specific function?
Huawei's "genius boy" Zhihui Jun has made a new work, creating a "customized" smart keyboard from scratch
Meeting OA project pending meeting, all meeting functions
TypeScript在使用中出现的问题记录
Image processing tool design
ShardingSphere's unsharded table configuration combat (6)
系统设计.短链系统设计
background has no effect on child elements of float
Unity2D horizontal version game tutorial 4 - item collection and physical materials
MySQL table design for message queue to store message data
【愚公系列】2022年07月 Go教学课程 019-循环结构之for









