I'm practicing Python. Being completely new to the language I'd like to hear someone else thoughts on the way I use the language. I'm coming from (mainly) Java and C so I'd expect new ways of doing stuff offered by Python which I am surely not aware of because I'm still learning.
I came up with a very simple implementation for a binary tree. The idea is to practice with classes in Python. The tree supports just inserting elements and traversing pre-order, in-order and post-order. I'm not concerned about the functionality but more about comments.
from __future__ import print_function
import math
import os
class BinaryTree:
__left = None
__right = None
__value = None
def __init__(self):
return
def addValue(self, value):
if self.__value is None:
self.__value = value
elif value > self.__value:
if self.__right is None:
self.__right = BinaryTree()
self.__right.addValue(value)
elif value < self.__value:
if self.__left is None:
self.__left = BinaryTree()
self.__left.addValue(value)
return
def preOrderTraverse(self):
"""
Performs a pre-order traversal of the tree.
Returns the list of elements
"""
elements = []
if self.__value is not None:
# Visit the root node first
elements.append(self.__value)
# Then visit the left node if present
if self.__left is not None:
elements += self.__left.preOrderTraverse()
# Then visit the right node if present
if self.__right is not None:
elements += self.__right.preOrderTraverse()
return elements
def inOrderTraverse(self):
"""
Performs a in-order traversal of the tree.
Returns the list of elements
"""
elements = []
if self.__value is not None:
# Visit the left node first if present
if self.__left is not None:
elements += self.__left.inOrderTraverse()
# Then visit the root node
elements.append(self.__value)
# Then visit the right node if present
if self.__right is not None:
elements += self.__right.inOrderTraverse()
return elements
def postOrderTraverse(self):
"""
Performs a post-order traversal of the tree.
Returns the list of elements
"""
elements = []
if self.__value is not None:
# Visit the left node first if present
if self.__left is not None:
elements += self.__left.postOrderTraverse()
# Then visit the right node if present
if self.__right is not None:
elements += self.__right.postOrderTraverse()
# Then visit the root node
elements.append(self.__value)
return elements
if __name__ == "__main__":
binarytree = BinaryTree()
binarytree.addValue(23)
binarytree.addValue(15)
binarytree.addValue(19)
binarytree.addValue(8)
binarytree.addValue(7)
binarytree.addValue(42)
binarytree.addValue(0)
binarytree.addValue(1)
elements = binarytree.preOrderTraverse()
print("Pre order traversal: ", end="")
for val in elements:
print(val, end=" ")
print("")
elements = binarytree.inOrderTraverse()
print("In order traversal: ", end="")
for val in elements:
print(val, end=" ")
print("")
elements = binarytree.postOrderTraverse()
print("Post order traversal: ", end="")
for val in elements:
print(val, end=" ")
print("")