BST二叉搜索树查找节点元素,binarytree,Python

x33g5p2x  于2021-12-07 转载在 Python  
字(0.7k)|赞(0)|评价(0)|浏览(317)

BST二叉搜索树查找节点元素,binarytree,Python

  1. import random
  2. import binarytree
  3. def app():
  4. t = binarytree.bst(height=5, is_perfect=False)
  5. print(t)
  6. print('-----')
  7. idx = random.randint(1, t.size - 1)
  8. target = t.levelorder[idx].value # 从节点中随机找一个值
  9. print('查找', target)
  10. path = search(t, target)
  11. print('路线', path)
  12. def search(node, target):
  13. path = []
  14. while True:
  15. path.append(node)
  16. if node.value == target:
  17. break
  18. if node is not None:
  19. if target > node.value:
  20. node = node.right
  21. else:
  22. node = node.left
  23. return path
  24. if __name__ == '__main__':
  25. app()

运行日志输出:

  1. __2__________________________________
  2. / \
  3. 0 ___________________60___
  4. \ / \
  5. 1 _________36______ _62
  6. / \ /
  7. 4___ ____39___ 61
  8. / \ / \
  9. 3 _31 37 _45
  10. / \ \ / \
  11. 23 33 38 43 49
  12. -----
  13. 查找 45
  14. 路线 [Node(2), Node(60), Node(36), Node(39), Node(45)]

相关文章