当前位置:网站首页>Xiaohei's leetcode journey: 117. Fill the next right node pointer of each node II
Xiaohei's leetcode journey: 117. Fill the next right node pointer of each node II
2022-07-31 00:58:00 【little black invincible】
层次遍历法
""" # 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
# Generate a linked list of child nodes
def handle(node):
# The linked list has the previous 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
# The child node linked list is generated from the previous linked list
while p:
if p.left:
handle(p.left)
if p.right:
handle(p.right)
p = p.next
# next linked list starts
self.start = self.nextStart
return root

边栏推荐
猜你喜欢
随机推荐
The level of ShardingSphere depots in actual combat (4)
How to Add a Navigation Menu on Your WordPress Site
SereTOD2022 Track2 Code Analysis - Task-based Dialogue Systems Challenge for Semi-Supervised and Reinforcement Learning
《实战》基于电商领域的词性提取及其决策树模型建模
Mysql:Invalid default value for TIMESTAMP
(5) fastai application
ShardingSphere's unsharded table configuration combat (6)
typescript12-联合类型
Basic usage of async functions and await expressions in ES6
BOM系列之history对象
WEB Security Basics - - - Vulnerability Scanner
Zabbix干啥用?
Huawei's "genius boy" Zhihui Jun has made a new work, creating a "customized" smart keyboard from scratch
认识DTU什么是4GDTU设备
typescript15-(同时指定参数和返回值类型)
剑指offer17---打印从1到最大的n位数
typescript18-对象类型
ELK部署脚本---亲测可用
ABC 261 F - Sorting Color Balls (reverse pair)
小黑leetcode之旅:117. 填充每个节点的下一个右侧节点指针 II









