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
|
|
|
|
2015-08-05 18:14:44 +08:00
|
|
|
def __str__(self):
|
|
|
|
return str(self.data)
|
|
|
|
|
|
|
|
|
2015-08-02 05:44:14 +08:00
|
|
|
def insert(root, data):
|
2016-06-24 19:23:20 +08:00
|
|
|
# Constraint: Assume we are working with valid ints
|
2016-03-01 20:03:37 +08:00
|
|
|
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:
|
2016-06-24 19:23:20 +08:00
|
|
|
root.left = insert(root.left, data)
|
2015-08-16 20:21:11 +08:00
|
|
|
root.left.parent = root
|
2016-06-26 09:03:26 +08:00
|
|
|
return root.left
|
2015-08-02 05:44:14 +08:00
|
|
|
else:
|
2016-06-26 09:03:26 +08:00
|
|
|
return insert(root.left, data)
|
2015-08-02 05:44:14 +08:00
|
|
|
else:
|
|
|
|
if root.right is None:
|
2016-06-24 19:23:20 +08:00
|
|
|
root.right = insert(root.right, data)
|
2015-08-16 20:21:11 +08:00
|
|
|
root.right.parent = root
|
2016-06-26 09:03:26 +08:00
|
|
|
return root.right
|
2015-08-02 05:44:14 +08:00
|
|
|
else:
|
2016-06-26 09:03:26 +08:00
|
|
|
return insert(root.right, data)
|