【发布时间】:2017-06-28 08:29:13
【问题描述】:
所以我有一个二叉搜索树,我正在尝试获取所述树的高度。我有一个 self.height 属性,当我执行 insert_element(self, value) 时它会增加,而当 remove_element(self, value) 发生时会减少。但是,我注意到每次发生其中一种方法时都会增加和减少,并且没有考虑节点是否处于相同的高度而不会改变高度。
class Binary_Search_Tree:
class __BST_Node:
def __init__(self, value):
self.value = value
self.lchild = None
self.rchild = None
def __init__(self):
self.__root = None
self.height = 0
def insert_element(self, value):
self._insert(self.__root, value)
def _insert(self, root, value):
node = Binary_Search_Tree.__BST_Node(value)
if root == value:
raise ValueError("Value already exists")
if self.__root is None:
self.__root = Binary_Search_Tree.__BST_Node(value)
self.height += 1
return self.__root
else:
if root.value > node.value:
if root.lchild is None:
root.lchild = node
self.height += 1
return root.lchild
else:
self._insert(root.lchild, value)
elif root.value < node.value:
if root.rchild is None:
root.rchild = node
self.height += 1
return root.rchild
else:
self._insert(root.rchild, value)
return root
def remove_element(self, value):
self.__root = self._remove(self.__root, value)
self.height -= 1
return self.__root
def _remove(self, root, value):
if self.__root is None:
raise ValueError("Tree is empty")
if root.value != value:
raise ValueError("No such value")
if root.value == value:
if root.lchild is None and root.rchild is None:
root = None
self.height -= 1
return root
elif root.lchild is None or root.rchild is None:
if root.lchild is None:
self.height -= 1
return root.rchild
if root.rchild is None:
self.height -= 1
return root.lchild
elif root.lchild and root.rchild:
parent = root
successor = root.rchild
while successor.lchild:
parent = successor
successor = successor.lchild
root.value = successor.value
if parent.lchild == successor:
parent.lchild = successor.rchild
self.height -= 1
return parent.lchild
else:
parent.rchild = successor.rchild
self.height -= 1
return parent.rchild
else:
if root.value > value:
if root.lchild:
root.lchild = self._remove(root.lchild, value)
elif root.value < value:
if root.rchild:
root.rchild = self._remove(root.rchild, value)
return root
def in_order(self):
if self.__root is not None:
self._in(self.__root)
def _in(self, root):
if root is None:
return
if root is not None:
self._in(root.lchild)
print(str(root.value))
self._in(root.rchild)
def get_height(self):
print(str(self.height))
def __str__(self):
return self.in_order()
if __name__ == '__main__':
pass
【问题讨论】:
-
有答案here。
-
一方面,你错误地处理了已经存在的值,插入了
if root == value:。此外,在通过比较值评估它应该在哪里之前,您不应该真正创建节点元素。
标签: python recursion binary-search-tree