interactive-coding-challenges/graphs_trees/bst/bst.py

31 lines
798 B
Python
Raw Normal View History

2015-08-02 05:44:14 +08:00
class Node(object):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.parent = None
2015-08-02 05:44:14 +08:00
def __str__(self):
return str(self.data)
2015-08-02 05:44:14 +08:00
def insert(root, data):
# Constraint: Assume we are working with valid ints
if root is None:
root = Node(data)
return root
2015-08-02 05:44:14 +08:00
if data <= root.data:
if root.left is None:
root.left = insert(root.left, data)
root.left.parent = root
return root.left
2015-08-02 05:44:14 +08:00
else:
return insert(root.left, data)
2015-08-02 05:44:14 +08:00
else:
if root.right is None:
root.right = insert(root.right, data)
root.right.parent = root
return root.right
2015-08-02 05:44:14 +08:00
else:
return insert(root.right, data)