当前位置:网站首页>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
边栏推荐
猜你喜欢
Shell programming of conditional statements
Mysql systemized JOIN operation example analysis
【952. Calculate the maximum component size according to the common factor】
typescript17-函数可选参数
Kotlin协程:协程上下文与上下文元素
This project is so geeky
Preparations for web vulnerabilities
ShardingSphere之水平分库实战(四)
Huawei's "genius boy" Zhihui Jun has made a new work, creating a "customized" smart keyboard from scratch
RTL8720DN开发笔记一 环境搭建与mqtt实例
随机推荐
MySql data recovery method personal summary
MySQL triggers
埃拉托斯特尼筛法
【愚公系列】2022年07月 Go教学课程 016-运算符之逻辑运算符和其他运算符
MySQL database constraints, table design
射频器件的基本参数1
Redis learning
WEB Security Basics - - - Vulnerability Scanner
typescript9-常用基础类型
MySQL——数据库的查,增,删
Sping.事务的传播特性
DOM系列之 client 系列
ECCV 2022丨轻量级模型架构火了,力压苹果MobileViT(附代码和论文下载)
GO GOPROXY代理设置
typescript13 - type aliases
TypeScript在使用中出现的问题记录
297. 二叉树的序列化与反序列化
分布式.幂等性
小程序-全局数据共享
MySQL table design for message queue to store message data