Skip to content

Commit c1b309b

Browse files
committed
9.27
1 parent 0b7823a commit c1b309b

File tree

1 file changed

+96
-0
lines changed

1 file changed

+96
-0
lines changed

7.py

+96
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
"""
2+
Definition of TreeNode:
3+
"""
4+
class TreeNode:
5+
def __init__(self, val):
6+
self.val = val
7+
self.left, self.right = None, None
8+
def printself(self):
9+
stack = []
10+
arr = []
11+
stack.append(self)
12+
while len(stack) != 0:
13+
if stack[0] != '#':
14+
arr.append(stack[0].val)
15+
if stack[0].left == None:
16+
stack.append('#')
17+
else :
18+
stack.append(stack[0].left)
19+
if stack[0].right == None:
20+
stack.append('#')
21+
else :
22+
stack.append(stack[0].right)
23+
else: arr.append('#')
24+
stack.pop(0)
25+
print("print: ", arr)
26+
27+
class Solution:
28+
"""
29+
@param root: An object of TreeNode, denote the root of the binary tree.
30+
This method will be invoked first, you should design your own algorithm
31+
to serialize a binary tree which denote by a root node to a string which
32+
can be easily deserialized by your own "deserialize" method later.
33+
"""
34+
def serialize(self, root):
35+
# write your code here
36+
res = []
37+
if root == None: return res
38+
stack = []
39+
stack.append(root)
40+
while(len(stack) != 0):
41+
if stack[0] != None:
42+
res.append(stack[0].val)
43+
stack.append(stack[0].left)
44+
stack.append(stack[0].right)
45+
else:
46+
res.append('#')
47+
stack.pop(0)
48+
return res
49+
50+
"""
51+
@param data: A string serialized by your serialize method.
52+
This method will be invoked second, the argument data is what exactly
53+
you serialized at method "serialize", that means the data is not given by
54+
system, it's given by your own serialize method. So the format of data is
55+
designed by yourself, and deserialize it here as you serialize it in
56+
"serialize" method.
57+
"""
58+
def deserialize(self, data):
59+
# write your code here
60+
stack = []
61+
left = True
62+
if len(data) == 0: return None
63+
else:
64+
root = TreeNode(data[0])
65+
stack.append(root)
66+
index = 1
67+
while len(stack) != 0 and index < len(data):
68+
if data[index] == '#':
69+
if left:
70+
left = False
71+
else:
72+
stack.pop(0)
73+
left = True
74+
else:
75+
if left:
76+
stack[0].left = TreeNode(data[index])
77+
stack.append(stack[0].left)
78+
left = False
79+
else:
80+
stack[0].right = TreeNode(data[index])
81+
stack.append(stack[0].right)
82+
left = True
83+
stack.pop(0)
84+
index += 1
85+
return root
86+
87+
testroot = TreeNode(3)
88+
testroot.left = TreeNode(9)
89+
testroot.right = TreeNode(20)
90+
testroot.right.left = TreeNode(15)
91+
testroot.right.right = TreeNode(7)
92+
testroot.printself()
93+
print(Solution.serialize(testroot, testroot))
94+
testarr = [3, 9, 20, '#', '#', 15, 7]
95+
resroot = Solution.deserialize(testarr, testarr)
96+
resroot.printself()

0 commit comments

Comments
 (0)