摘要:我知道如何在Python中构建二进制树。我知道如何遍历它。我甚至知道如何在该BTree中搜索特定值;但是,我无法弄清楚如何仅遍历二叉树的部分。
目标:我有500万个+数据点。我想查找比所讨论的值 所有数据点(例如:所有点数小于40,000)。我的基本逻辑如下:
我的代码:
class node:
def __init__(self, value=None):
self.value = value
self.left_child = None
self.right_child = None
class binary_search_tree:
def __init__(self):
self.root = None
def insert(self, value):
if self.root is None:
self.root = node(value)
else:
self._insert(value, self.root)
def _insert(self, value, cur_node):
if value < cur_node.value:
if cur_node.left_child is None:
cur_node.left_child = node(value)
else:
self._insert(value, cur_node.left_child)
elif value > cur_node.value:
if cur_node.right_child is None:
cur_node.right_child = node(value)
else:
self._insert(value, cur_node.right_child)
else:
print('Value already in tree!')
def print_tree(self):
if self.root is not None:
self._print_tree(self.root)
def _print_tree(self, cur_node):
if cur_node is not None:
self._print_tree(cur_node.left_child)
print(str(cur_node.value))
self._print_tree(cur_node.right_child)
def height(self):
if self.root is not None:
return self._height(self.root, 0)
else:
return 0
def _height(self, cur_node, cur_height):
if cur_node is None:
return cur_height
left_height = self._height(cur_node.left_child, cur_height+1)
right_height = self._height(cur_node.right_child, cur_height+1)
return max(left_height, right_height)
def print_trav_tree(self):
return self._print_trav_tree(self.root)
def _print_trav_tree(self, start):
#Root -> left -> right
traversal = ""
if start:
traversal += (str(start.value) + "-")
traversal = self._print_trav_tree(start.left_child)
traversal = self._print_trav_tree(start.right_child)
return traversal
def search(self, value):
if self.root is not None:
return self._search(value, self.root)
else:
return False
def _search(self, value, cur_node):
int_val = 0
if value == cur_node.value:
int_val = cur_node.value
elif value < cur_node.value and cur_node.left_child is not None:
int_val = self._search(value, cur_node.left_child)
elif value > cur_node.value and cur_node.right_child is not None:
int_val = self._search(value, cur_node.right_child)
else:
int_val = cur_node.value
#return -1
if int_val == -1:
int_val = cur_node.value
return int_val
def main():
tree = binary_search_tree()
tree.insert(666)
tree.insert(888)
tree.insert(88)
tree.insert(0)
tree.insert(55)
tree.insert(143)
tree.insert(193)
tree.insert(52)
tree.insert(21)
tree.insert(10)
tree.print_tree()
print("tree height is: " + str(tree.height()) + "\n")
print(tree.search(10))
print(tree.search(777))
print(tree.search(199))
jack = tree.print_trav_tree()
print(jack)
if __name__ == "__main__":
main()
任何帮助都会很棒!