-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrees.py
More file actions
69 lines (50 loc) · 1.54 KB
/
trees.py
File metadata and controls
69 lines (50 loc) · 1.54 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
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
from pprint import pprint as pp
# Binary Tree Class
class Tree:
def __init__(self, data, left, right):
self.data = data
self.left = left
self.right = right
# Multiway Tree Class
class Tree2:
def __init__(self, kids, next=None):
self.kids = self.val = kids
self.next = next
# Sample Tree
""" 0
1 2
3 4 6
9 10 11
"""
t = Tree(2, Tree(7, Tree(2,None,None), Tree(6, Tree(5,None, None), Tree(11,None,None))), Tree(5,None,Tree(9, Tree(4,None,None), None)))
# Recursively traverse a binary tree
# ==================================
# Preorder traversal keeps traversing the left most part of the
# tree until a leaf node (which has no child nodes) is encountered,
# then it goes up the tree, goes to the right child node (if any),
# and then goes up the tree again, and then as far left as possible,
# and this keeps repeating until all of the nodes are traversed.
def preorder(node):
if node is None:
return
print(node.data, end=" ")
preorder(node.left)
preorder(node.right)
def inorder(node):
if node is None:
return
inorder(node.left)
print(node.data, end=" ")
inorder(node.right)
def postorder(node):
if node is None:
return
postorder(node.left)
postorder(node.right)
print(node.data, end=" ")
title = "Preorder, Inorder, and Postorder Traversal of Binary Tree"
print(title)
print("="*len(title))
preorder(t); print()
inorder(t); print()
postorder(t); print()