-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstruct_string_from_binary_tree.py
More file actions
38 lines (34 loc) · 1.1 KB
/
construct_string_from_binary_tree.py
File metadata and controls
38 lines (34 loc) · 1.1 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
# Problem: Construct String from Binary Tree
# (https://leetcode.com/problems/construct-string-from-binary-tree/#/description)
# Appended to an array instead of string concatentation since each append is O(1)
# instead of O(n) concat
# 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 tree2List(self, t, treeList):
if t == None:
return ""
treeList.append(str(t.val))
if t.left != None:
treeList.append("(")
self.tree2List(t.left, treeList)
treeList.append(")")
elif t.left == None and t.right != None:
treeList.append("(")
treeList.append(")")
if t.right != None:
treeList.append("(")
self.tree2List(t.right, treeList)
treeList.append(")")
def tree2str(self, t):
"""
:type t: TreeNode
:rtype: str
"""
treeList = []
self.tree2List(t, treeList)
return "".join(treeList)