114. Flatten Binary Tree to Link
2019-05-30 本文已影响0人
云外雁行斜丶
114. Flatten Binary Tree to Linked List
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
First
根据栈的思想,通过深度优先遍历将所有的节点退出栈中,再由栈弹出每个节点进行拼接
from quixote.structs.tree import TreeNode
class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: None Do not return anything, modify root in-place instead.
"""
self.stack = []
self.dfs(root)
print(self.stack)
tmp = None
while self.stack:
node = self.stack.pop()
node.right = tmp
tmp = node
return tmp
def dfs(self, root):
self.stack.append(root)
if root.left:
self.dfs(root.left)
if root.right:
self.dfs(root.right)