-
Notifications
You must be signed in to change notification settings - Fork 0
/
4. Traversals.py
43 lines (34 loc) · 1.08 KB
/
4. Traversals.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
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def getTreeTraversal(root):
def preorder(node, result):
if node:
result.append(node.data)
preorder(node.left, result)
preorder(node.right, result)
def inorder(node, result):
if node:
inorder(node.left, result)
result.append(node.data)
inorder(node.right, result)
def postorder(node, result):
if node:
postorder(node.left, result)
postorder(node.right, result)
result.append(node.data)
inorder_result = []
preorder_result = []
postorder_result = []
inorder(root, inorder_result)
preorder(root, preorder_result)
postorder(root, postorder_result)
result = (
" ".join(map(str, inorder_result)) + "\n" +
" ".join(map(str, preorder_result)) + "\n" +
" ".join(map(str, postorder_result))
)
return result
# Link: https://www.naukri.com/code360/problems/tree-traversal_981269