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