-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathInorderTraversal.py
66 lines (52 loc) · 1.57 KB
/
InorderTraversal.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
# Problem Description: https://practice.geeksforgeeks.org/problems/inorder-traversal/1
from collections import defaultdict
class Node:
def __init__(self, val):
self.data = val
self.right = None
self.left = None
class Tree:
def __init__(self):
self.root = None
self.map_nodes = defaultdict(Node)
def insert(self, parent, child, dir):
if(not self.root):
root_node = Node(parent)
child_node = Node(child)
if(dir == 'L'):
root_node.left = child_node
elif(dir == 'R'):
root_node.right = child_node
self.root = root_node
self.map_nodes[parent] = root_node
self.map_nodes[child] = child_node
return
parent_node = self.map_nodes[parent]
child_node = Node(child)
if(dir == 'L'):
parent_node.left = child_node
elif(dir == 'R'):
parent_node.right = child_node
self.map_nodes[child] = child_node
return
def inorder(root):
if(not root):
return
if(root.left):
inorder(root.left)
print(root.data, end=" ")
if(root.right):
inorder(root.right)
if __name__ == "__main__":
t = int(input())
for _ in range(t):
n = int(input())
a = [x for x in input().split()]
tree = Tree()
for i in range(0, len(a), 3):
parent = a[i]
child = a[i+1]
dir = a[i+2]
tree.insert(parent, child, dir)
inorder(tree.root)
print()