btree_2.py

#! /usr/bin/python3
# ==================================================================
# From: www.tutorialspoint.com/python/python_binary_tree.htm
# ==================================================================

class Node:
    '''binary tree node class'''

    # ---- initialize binary tree node
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data

    # ---- insert node into tree
    def insert(self, data):
        if self.data:
            if data < self.data:
                if self.left is None:
                    self.left = Node(data)
                else:
                    self.left.insert(data)
            elif data > self.data:
                if self.right is None:
                    self.right = Node(data)
                else:
                    self.right.insert(data)
            else:
                print("Tree value " + str(data) +
                      " already in the tree")
        else:
            self.data = data

    # ---- print the tree
    def PrintTree(self):
        if self.left:
            self.left.PrintTree()
        print(self.data)
        if self.right:
            self.right.PrintTree()

# ---- create a binary tree

# test tree 1
#root = Node(12)
#root.insert(6)
#root.insert(14)
#root.insert(3)

# test tree 2
root = Node(27)
root.insert(14)
root.insert(35)
root.insert(10)
root.insert(19)
root.insert(19)              # duplicate node value
root.insert(31)
root.insert(42)

root.PrintTree()