Implement a tree data structure in Python. The following code shows how to implement a tree in the Python programming language.
Code:
class Node:
def __init__(self, data):
self.data = data
self.parent = None
self.left = None
self.right = None
def __repr__(self):
return repr(self.data)
def add_left(self, node):
self.left = node
if node is not None:
node.parent = self
def add_right(self, node):
self.right = node
if node is not None:
node.parent = self
class Tree:
def __init__(self):
self.root = None
def make_tree(self):
node_one = Node(1)
node_two = Node(2)
node_three = Node(3)
node_four = Node(4)
node_five = Node(5)
node_six = Node(6)
node_seven = Node(7)
node_eight = Node(8)
node_nine = Node(9)
node_ten = Node(10)
self.root = node_two
node_two.add_left(node_seven)
node_two.add_right(node_nine)
node_seven.add_left(node_one)
node_seven.add_right(node_six)
node_six.add_left(node_five)
node_six.add_right(node_ten)
node_nine.add_right(node_eight)
node_eight.add_left(node_three)
node_eight.add_right(node_four)
def pre_order(self, node):
print(node, end=' ')
if node.left:
self.pre_order(node.left)
if node.right:
self.pre_order(node.right)
def post_order(self, node):
if node.left:
self.post_order(node.left)
if node.right:
self.post_order(node.right)
print(node, end=' ')
def in_order(self, node):
if node.left:
self.in_order(node.left)
print(node, end=' ')
if node.right:
self.in_order(node.right)
if __name__ == '__main__':
tree = Tree()
tree.make_tree()
print('Pre order')
tree.pre_order(tree.root)
print('\nPost order')
tree.post_order(tree.root)
print('\nIn order')
tree.in_order(tree.root)
print('\nDone')
Output:
Pre order
2 7 1 6 5 10 9 8 3 4
Post order
1 5 10 6 7 3 4 8 9 2
In order
1 7 5 6 10 2 9 3 8 4
Done