-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetutil.py
59 lines (52 loc) · 1.33 KB
/
leetutil.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
47
48
49
50
51
52
53
54
55
56
57
58
59
#python2 or python3
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def buildList(vals):
ret = [ListNode(v) for v in vals]
for i in range(len(ret)-1):
ret[i].next = ret[i+1]
return ret
def printList(head):
s = []
while head:
s.append(str(head.val))
head = head.next
print(" ".join(s))
def buildTree(vals):
if isinstance(vals, list):
root = TreeNode(vals[0])
root.left = buildTree(vals[1])
root.right = buildTree(vals[2])
return root
elif vals != None: #single value
return TreeNode(vals)
def printTree(root, indent=0):
tab = " "
if root:
print("{}{}".format(tab*indent, root.val))
printTree(root.left, indent+1)
printTree(root.right, indent+1)
if __name__ == "__main__":
tree = r'''
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
[5,[4, [11, 7, 2], None], [8, 13, [4, 5, 1]]]
'''
print(tree)
root = buildTree([5,[4, [11, 7, 2], None], [8, 13, [4, 5, 1]]])
printTree(root)
print("*" * 16)
head = buildList([1,2,3,4,5])[0]
printList(head)