将二叉树拆成链表

中文English

将一棵二叉树按照前序遍历拆解成为一个 假链表。所谓的假链表是说,用二叉树的 right 指针,来表示链表中的 next 指针。

Example

样例 1:

输入:{1,2,5,3,4,#,6}
输出:{1,#,2,#,3,#,4,#,5,#,6}
解释:
1
/ \
2 5
/ \ \
3 4 6 1
\
2
\
3
\
4
\
5
\
6

样例 2:

输入:{1}
输出:{1}
解释:
1
1

Challenge

不使用额外的空间耗费。

Notice

不要忘记将左儿子标记为 null,否则你可能会得到空间溢出或是时间溢出。

"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
""" class Solution:
"""
@param root: a TreeNode, the root of the binary tree
@return: nothing
"""
def flatten(self, root):
# write your code here
if not root:
return
last_node = dummy = TreeNode(None)
stack = [root]
while stack:
node = stack.pop()
last_node.right = node
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
node.left, node.right = None, None
last_node = node
class Solution:
last_node = None """
@param root: a TreeNode, the root of the binary tree
@return: nothing
"""
def flatten(self, root):
if root is None:
return if self.last_node is not None:
self.last_node.left = None
self.last_node.right = root self.last_node = root
right = root.right
self.flatten(root.left)
self.flatten(right)

 后者是使用递归的解法。但是要注意变量修改的细节。

 需要在遍历中记住上次遍历节点,根据上次的节点和当前节点进行比较而得到result的算法模板:

class Solution():
last_node = None
result = None def run(self, root):
self.dfs(root)
return self.result def dfs(self):
if last_node is None:
last_node = root
else:
do_sth(last_node, root) dfs(root.left) dfs(root.right)

  

  

最新文章

  1. BCP导出导入大容量数据实践
  2. Python 文件读写,条件循环(三次登录锁定账号实例)
  3. mysql 的2个关于事务和安全性的参数
  4. 用自己的算法实现startsWith和endsWith功能
  5. python_way ,day22 tonardo
  6. iOS产品开发流程
  7. Android Studio Check for Update
  8. 如何在ARC代码中混编非ARC代码
  9. web工程中URL地址的写法
  10. Android 发送HTTP GET POST 请求以及通过 MultipartEntityBuilder 上传文件
  11. EasyUI-datagrid获取编辑行的数据
  12. webpack入门篇--1.简单介绍
  13. netty的基本介绍
  14. k64 datasheet学习笔记22---Direct Memory Access Controller (eDMA)
  15. 潭州课堂25班:Ph201805201 爬虫高级 第十二 课 Scrapy-redis分布 项目实战 (课堂笔记)
  16. Mybatis返回值类型是hashmap,输入键值对为空时,key 丢失的问题
  17. [VS工具]如何让#region...#endregion在ashx文件页面上折叠
  18. Adroid我还是个菜鸟——导入jar包
  19. /var/log/messages Logging not working on Centos 7
  20. VMware Coding Challenge: Possible Scores && Summary: static

热门文章

  1. jenkins pipeline使用方式
  2. Elasticsearch运维经验总结
  3. github执行clone操作时报错
  4. CentOS安装SonarQube7.9.1
  5. WeakhashMap源码1
  6. HTML5微信长按图片不会弹出菜单的解决方法
  7. 【剑指offer】数据流中的中位数
  8. 如何在Typora中使用流程图
  9. Java学习:接口(interface)的使用于注意事项
  10. python中 jsonchema 与 shema 效率比较