Since we have to write code for inserting an element into binary tree then we must know what is Binary tree.
Def of Binary tree: A tree is called binary tree, if each node has zero child, one child or two child.Empty tree is also a valid binary tree.So the idea is , if we find a node whose left child is empty , we make new key as left child of the node, else if we
find a node whose right side is empty, we make new key as right child of the node.We keep traversing the
tree until we find a node whose either left or right child is empty.
Program:
def __init__(self, data):
def insertLeft(self, newnode):
if self.left == None:
self.left = newnode
else:
newnode.left = self.left
self.left = newnode
def insertRight(self, newnode):
if self.right == None:
self.right = newnode
else:
newnode.right = self.right
self.right = newnode
newnode.right = self.right
def preorderR(self, a=None):
if not a:
a = self
print(a.data)
if a.left:
self.preorderR(a.left)
if a.right:
self.preorderR(a.right)
print("Level Order Traversing:")
q = queue.Queue()
result = []
q.put(self)
while not q.empty():
node = q.get()
result.append(node.getData())
result.append(node.getData())
if node.getLeft():
q.put(node.getLeft())
if node.getRight():
q.put(node.getRight())
print(result)
A = BinaryTreeNode(
A = BinaryTreeNode("A")
B = BinaryTreeNode(
B = BinaryTreeNode("B")
C = BinaryTreeNode(
C = BinaryTreeNode("C")
D = BinaryTreeNode(
D = BinaryTreeNode("D")
E= BinaryTreeNode(
E= BinaryTreeNode("E")
F = BinaryTreeNode(
F = BinaryTreeNode("F")
G = BinaryTreeNode(
G = BinaryTreeNode("G")
A.insertLeft(B)
A.insertRight(C)
B.insertLeft(D)
B.insertRight(E)
C.insertLeft(F)
C.insertRight(G)
print(
print("Pre-Order Recursive:")
A.preorderR()
A.levelOrder()
Pre-Order Recursive:
A
B
D
E
C
F
G
Level Order Traversing:
['A', 'B', 'C', 'D', 'E', 'F', 'G']
Comments