LintCode Q453 Flatten Binary Tree to Linked List in Python

  • Jinhai ZHOU
  • 4 Minutes
  • 2016年12月11日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.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
# time complexity: O(n)
# space complexity: O(n)
list = []
self.preOrder(root, list)
dummy = TreeNode(None)
current = dummy
for node in list:
node.right = None
node.left = None
current.right = node
current = node
return dummy.right
def preOrder(self, node, list):
if node is None:
return
list.append(node)
if node.left:
self.preOrder(node.left, list)
if node.right:
self.preOrder(node.right, list)
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。