---恢复内容开始---

题目描述:

方法一:层次遍历

"""
# 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

---恢复内容结束---

最新文章

  1. easyui表格的增删改查
  2. java的三大框架(二)---Struts2
  3. LVS相关学习
  4. JDBC的增删改写成一个方法,调用一个工具类
  5. 制作自己的ros机器人(navigaion)前提--22
  6. AngularJS 的安全Apply
  7. 树形动规--没有上司的舞会--C++
  8. 创建一个Hello World模块
  9. Linux中搭建SVN服务器
  10. iWeb峰会见闻
  11. find中的-print0和xargs中-0的区别
  12. Snail’s trouble
  13. Beta敏捷冲刺每日报告——Day1
  14. 接口自动化测试:python+json+requests+数据驱动
  15. 【LOJ565】【LibreOJ Round #10】mathematican 的二进制 DP 分治FFT
  16. thinkphp使用PHPExcel导出
  17. Tenka 1 Computer Contest C-Align
  18. hdu1251+字典树常用模板
  19. AWR不能自动生成快照
  20. input type=file 上传文件样式美化(转载)

热门文章

  1. opencv-霍夫直线变换与圆变换
  2. class1and2_tkinter之 Label & Button 标签和按钮
  3. DXP 常用功能
  4. CodeForces 1166E The LCMs Must be Large
  5. mysql 触发器实现级联删除有外键的多张表
  6. java 打印1到n之间的整数
  7. SQL语句转换成MapReduce的基本原理
  8. JS对象 提取指定数目的字符substr() substr() 方法从字符串中提取从 startPos位置开始的指定数目的字符串。
  9. mysql 的特殊函数
  10. C++ strcat_s