Given a binary tree, flatten it to a linked list in-place.

For example, given the following tree:

    1
/ \
2 5
/ \ \
3 4 6

The flattened tree should look like:

1
\
2
\
3
\
4
\
5
\
6

这个题思路就是DFS, 先左后右, 记住如果是用stack如果需要先得到左, 那么要先append右, 另外需要注意的就是用recursive方式的时候需要用一个temp来去存root.right, 否则用preorder的时候root.right就是丢了!

1. Constraints

1) can be empty

2. Ideas

DFS    T: O(n)     S:O(1)

用pre来存之前的node, 然后DFS

3. Code

3.1) iterable

 class Solution:
def flatten(self, root):
pre, stack = None, [root]
while stack:
node = stack.pop()
if node:
if pre:
pre.left = None # dont forget to set left as None
pre.right = node
pre = node
stack.append(node.right) # stack 先进后出
stack.append(node.left)

3.2) recursive

 class Solution:
def __init__(self):
self.pre = None
def flatten(self, root):
if not root: return
if self.pre:
self.pre.left = None
self.pre.right = root
self.pre = root
temp = root.right # otherwise we will lose the root.right
self.flatten(root.left)
self.flatten(root.right)

4. Test cases

1) None

2)

    1
/ \
2 5
/ \ \
3 4 6

最新文章

  1. python之路4
  2. String Date Calendar之间的转换
  3. 如何让aspnet服务加载静态资源html(我的动态网页静态化) 转
  4. Python的禅,“提姆彼得斯”说的非常有道理道出了这门编程语言的真谛!
  5. Mathematics:Semi-prime H-numbers(POJ 3292)
  6. (转)修改ECSHOP前后台的title中的ecshop
  7. 给Visual Studio更替皮肤和背景图
  8. 1688: [Usaco2005 Open]Disease Manangement 疾病管理( 枚举 )
  9. 通用类 对象Excel互转
  10. 下载RDO OpenStack RPM
  11. admin 显示多对多字段
  12. Kali下Ettercap 使用教程+DNS欺骗攻击
  13. C/C++ 下的void main()
  14. poj 1182 (关系并查集) 食物链
  15. shell 命令 if [ -d filename] 判断文件
  16. Flask 进阶二
  17. POJ 3280 Cheapest Palindrome(区间DP求改成回文串的最小花费)
  18. [leetcode tree]101. Symmetric Tree
  19. Storm学习笔记——高级篇
  20. Windows Server 2003、2008、2012系统的安装

热门文章

  1. js - 预加载+监听图片资源加载制作进度条
  2. 为Gem 添加环境设定
  3. PCB常见的拓扑结构 (转)
  4. AngularJS初始(一)
  5. Making Promises With
  6. 170811、Java获取jdk系统环境变量
  7. easyui_2----messager
  8. Python之shutil模块
  9. POJ-1953 World Cup Noise(线性动规)
  10. python数据结构之树(二叉树的遍历)