当前位置:网站首页>小黑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
边栏推荐
- 【愚公系列】2022年07月 Go教学课程 016-运算符之逻辑运算符和其他运算符
- typescript16-void
- Error occurred while trying to proxy request The project suddenly can't get up
- XSS related knowledge
- Rocky/GNU之Zabbix部署(3)
- C语言力扣第48题之旋转图像。辅助数组
- A complete guide to avoiding pitfalls for the time-date type "yyyy-MM-dd HHmmss" in ES
- typescript18-对象类型
- Jmeter参数传递方式(token传递,接口关联等)
- Niuke.com question brushing training (4)
猜你喜欢
Mysql systemized JOIN operation example analysis
Responsive layout vs px/em/rem
typescript17-函数可选参数
Go 学习笔记(84)— Go 项目目录结构
Typescript14 - (type) of the specified parameters and return values alone
ShardingSphere之垂直分库分表实战(五)
WMware Tools installation failed segmentation fault solution
mysql主从复制及读写分离脚本-亲测可用
typescript9-常用基础类型
mysql索引失效的常见9种原因详解
随机推荐
【c语言课程设计】C语言校园卡管理系统
24. Please talk about the advantages and disadvantages of the singleton pattern, precautions, usage scenarios
SereTOD2022 Track2 Code Analysis - Task-based Dialogue Systems Challenge for Semi-Supervised and Reinforcement Learning
响应式布局与px/em/rem的比对
Basic usage of async functions and await expressions in ES6
什么是Promise?Promise的原理是什么?Promise怎么用?
ShardingSphere's public table combat (7)
分布式.分布式锁
孩子的编程启蒙好伙伴,自己动手打造小世界,长毛象教育AI百变编程积木套件上手
MySQL高级-六索引优化
WEB安全基础 - - -漏洞扫描器
Responsive layout vs px/em/rem
埃拉托斯特尼筛法
typescript13 - type aliases
Artificial Intelligence and Cloud Security
Solution: Parameter 0 of method ribbonServerList in com.alibaba.cloud.nacos.ribbon.NacosRibbonClientConfigu
Filter (Filter)
TypeScript在使用中出现的问题记录
【Yugong Series】July 2022 Go Teaching Course 017-IF of Branch Structure
[C language course design] C language campus card management system