2015-08-02 05:44:14 +08:00
|
|
|
class Node(object):
|
|
|
|
|
|
|
|
def __init__(self, data):
|
|
|
|
self.data = data
|
|
|
|
self.left = None
|
|
|
|
self.right = None
|
2015-08-16 20:21:11 +08:00
|
|
|
self.parent = None
|
2015-08-02 05:44:14 +08:00
|
|
|
|
2016-07-20 19:24:04 +08:00
|
|
|
def __repr__(self):
|
2015-08-05 18:14:44 +08:00
|
|
|
return str(self.data)
|
|
|
|
|
|
|
|
|
2016-08-14 20:20:06 +08:00
|
|
|
class Bst(object):
|
|
|
|
|
|
|
|
def __init__(self, root=None):
|
|
|
|
self.root = root
|
|
|
|
|
|
|
|
def insert(self, data):
|
|
|
|
if data is None:
|
|
|
|
raise Exception('Data cannot be None')
|
|
|
|
if self.root is None:
|
|
|
|
self.root = Node(data)
|
|
|
|
return self.root
|
|
|
|
return self._insert(self.root, data)
|
|
|
|
|
|
|
|
def _insert(self, node, data):
|
|
|
|
# Constraint: Assume we are working with valid ints
|
|
|
|
if node is None:
|
|
|
|
return Node(data)
|
|
|
|
if data <= node.data:
|
|
|
|
if node.left is None:
|
|
|
|
node.left = self._insert(node.left, data)
|
|
|
|
node.left.parent = node
|
|
|
|
return node.left
|
|
|
|
else:
|
|
|
|
return self._insert(node.left, data)
|
2015-08-02 05:44:14 +08:00
|
|
|
else:
|
2016-08-14 20:20:06 +08:00
|
|
|
if node.right is None:
|
|
|
|
node.right = self._insert(node.right, data)
|
|
|
|
node.right.parent = node
|
|
|
|
return node.right
|
|
|
|
else:
|
|
|
|
return self._insert(node.right, data)
|