Skip to content

Commit a3d2e03

Browse files
committed
Added binary tree implementation
1 parent 530d147 commit a3d2e03

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

pygorithm/data_structures/tree.py

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# Author: OMKAR PATHAK
2+
# Created On: 9th August 2017
3+
4+
# Node class to create a node for binary tree
5+
class Node(object):
6+
def __init__(self, data = None):
7+
self.left = None
8+
self.right = None
9+
self.data = data
10+
11+
# for setting left node
12+
def set_left(self, node):
13+
self.left = node
14+
15+
# for setting right node
16+
def set_right(self, node):
17+
self.right = node
18+
19+
# for getting the left node
20+
def get_left(self):
21+
return self.left
22+
23+
# for getting right node
24+
def get_right(self):
25+
return self.right
26+
27+
# for setting data of a node
28+
def set_data(self, data):
29+
self.data = data
30+
31+
# for getting data of a node
32+
def get_data(self):
33+
return self.data
34+
35+
# easily retrieve the source code of the Node class
36+
def get_code(self):
37+
import inspect
38+
return inspect.getsource(Node)
39+
40+
# BinaryTree class to create a binary tree
41+
class BinaryTree(object):
42+
def __init__(self):
43+
self._inorder = []
44+
self._preorder = []
45+
self._postorder = []
46+
47+
# in this we traverse first to the leftmost node, then print its data and then traverse for rightmost node
48+
def inorder(self, root):
49+
'''
50+
@type: root: Node object
51+
'''
52+
if root:
53+
self.inorder(root.get_left()) # traverse to leftmost child
54+
self._inorder.append(root.get_data()) # get the data of current node
55+
self.inorder(root.get_right()) # traverse to rightmost child
56+
return self._inorder
57+
58+
# in this we first print the root node and then traverse towards leftmost node and then to the rightmost node
59+
def preorder(self, root):
60+
'''
61+
@type: root: Node object
62+
'''
63+
if root:
64+
self._preorder.append(root.get_data()) # get the data of current node
65+
self.preorder(root.get_left()) # traverse to leftmost child
66+
self.preorder(root.get_right()) # traverse to rightmost child
67+
return self._preorder
68+
69+
# in this we first traverse to the leftmost node and then to the rightmost node and then print the data
70+
def postorder(self, root):
71+
'''
72+
@type: root: Node object
73+
'''
74+
if root:
75+
self.postorder(root.get_left()) # traverse to leftmost child
76+
self.postorder(root.get_right()) # traverse to rightmost child
77+
self._postorder.append(root.get_data()) # get the data of current node
78+
return self._postorder
79+
80+
# easily retrieve the source code of the BinaryTree class
81+
def get_code(self):
82+
import inspect
83+
return inspect.getsource(BinaryTree)

0 commit comments

Comments
 (0)