-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathother_method.py
More file actions
41 lines (34 loc) · 1.04 KB
/
Copy pathother_method.py
File metadata and controls
41 lines (34 loc) · 1.04 KB
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
# 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):
def tree2str(self, t):
"""
:type t: TreeNode
:rtype: str
"""
def preOrder(t):
if not t:
return ""
result.append(str(t.val))
# when t.left is null and t.right exists
if t.right and not t.left:
result.append("()(")
preOrder(t.right)
result.append(")")
else:
if t.left:
result.append("(")
preOrder(t.left)
result.append(")")
if t.right:
result.append("(")
preOrder(t.right)
result.append(")")
result = []
preOrder(t)
print result
return "".join(result)