Binary Search Tree - Insertion (Python)
suggest changeThis is a simple implementation of Binary Search Tree Insertion using Python.
An example is shown below:
![](/essential/algorithms/img/3c719051c4a0fd52fb5cb3e4b987af87aa132a93.gif)
Following the code snippet each image shows the execution visualization which makes it easier to visualize how this code works.
class Node:
def __init__(self, val):
self.l_child = None
self.r_child = None
self.data = val
![](/essential/algorithms/img/dc84ab95873d6e1ed63d55028da006608b910dde.png)
def insert(root, node):
if root is None:
root = node
else:
if root.data > node.data:
if root.l_child is None:
root.l_child = node
else:
insert(root.l_child, node)
else:
if root.r_child is None:
root.r_child = node
else:
insert(root.r_child, node)
![](/essential/algorithms/img/19f7596fd61e6ed081abfd3d76d377f62943495a.png)
def in_order_print(root):
if not root:
return
in_order_print(root.l_child)
print root.data
in_order_print(root.r_child)
![](/essential/algorithms/img/b820e971ec1a428198d469381ef9fccca0f7118c.png)
def pre_order_print(root):
if not root:
return
print root.data
pre_order_print(root.l_child)
pre_order_print(root.r_child)
![](/essential/algorithms/img/cd9727ebe627f663a9d36c5d0e12e603e69c0dcd.png)
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents