leetcode-117-填充每个节点的下一个右侧节点指针②
2024-09-02 14:41:11
---恢复内容开始---
题目描述:
方法一:层次遍历
"""
# Definition for a Node.
class Node:
def __init__(self, val, left, right, next):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:
return
stack = [root]
#ans = []
while stack:
tem_stack=[]
#tem_ans = []
for i in stack:
tem_ans.append(i.val)
if i.left:
tem_stack.append(i.left)
if i.right:
tem_stack.append(i.right)
if len(tem_stack)>1:
for i in range(len(tem_stack)-1):
tem_stack[i].next = tem_stack[i+1]
stack = tem_stack
#ans.append(tem_ans)
return root
方法二:迭代
class Solution:
def connect(self, root: 'Node') -> 'Node':
cur = root
head = None
tail = None
while cur:
while cur:
if cur.left:
if not head:
head = cur.left
tail = cur.left
else:
tail.next = cur.left
tail = tail.next
if cur.right:
if not head:
head = cur.right
tail = cur.right
else:
tail.next = cur.right
tail = tail.next
cur = cur.next
cur = head
head = None
tail = None
return root
---恢复内容结束---
最新文章
- easyui表格的增删改查
- java的三大框架(二)---Struts2
- LVS相关学习
- JDBC的增删改写成一个方法,调用一个工具类
- 制作自己的ros机器人(navigaion)前提--22
- AngularJS 的安全Apply
- 树形动规--没有上司的舞会--C++
- 创建一个Hello World模块
- Linux中搭建SVN服务器
- iWeb峰会见闻
- find中的-print0和xargs中-0的区别
- Snail’s trouble
- Beta敏捷冲刺每日报告——Day1
- 接口自动化测试:python+json+requests+数据驱动
- 【LOJ565】【LibreOJ Round #10】mathematican 的二进制 DP 分治FFT
- thinkphp使用PHPExcel导出
- Tenka 1 Computer Contest C-Align
- hdu1251+字典树常用模板
- AWR不能自动生成快照
- input type=file 上传文件样式美化(转载)
热门文章
- opencv-霍夫直线变换与圆变换
- class1and2_tkinter之 Label &; Button 标签和按钮
- DXP 常用功能
- CodeForces 1166E The LCMs Must be Large
- mysql 触发器实现级联删除有外键的多张表
- java 打印1到n之间的整数
- SQL语句转换成MapReduce的基本原理
- JS对象 提取指定数目的字符substr() substr() 方法从字符串中提取从 startPos位置开始的指定数目的字符串。
- mysql 的特殊函数
- C++ strcat_s