forked from SamirPaulb/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path114_Flatten_Binary_Tree_to_Linked_List.py
51 lines (43 loc) · 1.28 KB
/
114_Flatten_Binary_Tree_to_Linked_List.py
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
36
37
38
39
40
41
42
43
44
45
46
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
# stack
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
if root is None:
return
if root.left is None and root.right is None:
return
current = root
stack = [root]
while stack:
node = stack.pop()
self.appendNode(stack, node.right)
self.appendNode(stack, node.left)
if current != node:
current.right = node
current.left = None
current = node
def appendNode(self, stack, node):
if node:
stack.append(node)
# recursive
# https://discuss.leetcode.com/topic/11444/my-short-post-order-traversal-java-solution-for-share/2
# def __init__(self):
# self.prev = None
#
# def flatten(self, root):
# if root is None:
# return
# self.flatten(root.right)
# self.flatten(root.left)
# root.right = self.prev
# root.left = None
# self.prev = root