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

43 lines
1.1 KiB
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 __repr__(self):
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 TypeError('data cannot be None')
2016-08-14 20:20:06 +08:00
if self.root is None:
self.root = Node(data)
return self.root
else:
return self._insert(self.root, data)
2016-08-14 20:20:06 +08:00
def _insert(self, node, data):
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)