-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree-orders.py
executable file
·87 lines (67 loc) · 2.53 KB
/
tree-orders.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# Binary Tree Traversals
# author: jerrybelmonte
import sys
import threading
sys.setrecursionlimit(10 ** 7) # max depth of recursion
threading.stack_size(2 ** 27) # new thread will get stack of such size
class TreeOrders:
def __init__(self):
self.n = int(sys.stdin.readline())
self.key = [0 for i in range(self.n)]
self.left = [0 for i in range(self.n)]
self.right = [0 for i in range(self.n)]
def read(self):
for i in range(self.n):
[a, b, c] = map(int, sys.stdin.readline().split())
self.key[i] = a
self.left[i] = b
self.right[i] = c
def in_order(self):
result = []
self._in_order_recursive(result, 0)
return result
def _in_order_recursive(self, arr, ndx):
if ndx != -1:
# visit the left subtree first
if self.left[ndx] != -1:
self._in_order_recursive(arr, self.left[ndx])
# add the key value of the current node
arr.append(self.key[ndx])
# visit the right subtree last
if self.right[ndx] != -1:
self._in_order_recursive(arr, self.right[ndx])
def pre_order(self):
result = []
self._pre_order_recursive(result, 0)
return result
def _pre_order_recursive(self, arr, ndx):
if ndx != -1:
# add the key value of the current node first
arr.append(self.key[ndx])
# visit the left subtree second
if self.left[ndx] != -1:
self._pre_order_recursive(arr, self.left[ndx])
# visit the right subtree last
if self.right[ndx] != -1:
self._pre_order_recursive(arr, self.right[ndx])
def post_order(self):
result = []
self._post_order_recursive(result, 0)
return result
def _post_order_recursive(self, arr, ndx):
if ndx != -1:
# visit the left subtree first
if self.left[ndx] != -1:
self._post_order_recursive(arr, self.left[ndx])
# visit the right subtree next
if self.right[ndx] != -1:
self._post_order_recursive(arr, self.right[ndx])
# add the key value of the current node last
arr.append(self.key[ndx])
def main():
tree = TreeOrders()
tree.read()
print(" ".join(str(x) for x in tree.in_order()))
print(" ".join(str(x) for x in tree.pre_order()))
print(" ".join(str(x) for x in tree.post_order()))
threading.Thread(target=main).start()