binarytree构建二叉树堆,python

x33g5p2x  于2021-11-14 转载在 Python  
字(0.9k)|赞(0)|评价(0)|浏览(351)

binarytree用来构建二叉树堆很便利,比如:

  1. from binarytree import tree, Node, build, get_parent
  2. def app():
  3. my_tree = tree(height=3, is_perfect=False)
  4. print(my_tree.pprint(index=True))
  5. print('-')
  6. root = Node(1) # index: 0, value: 1
  7. root.left = Node(2) # index: 1, value: 2
  8. root.right = Node(3) # index: 2, value: 3
  9. root.left.right = Node(value=4, left=Node(5), right=Node(6)) # index: 4, value: 4
  10. root.pprint(index=True)
  11. print('--')
  12. print(root)
  13. print('---')
  14. root.left.left = Node(15)
  15. print(root)
  16. print('----')
  17. root.right.right = root.left
  18. print(root)
  19. print('-----')
  20. root2 = build([1, 2, 3, 4, None, 5])
  21. print(root2)
  22. print('------')
  23. print(get_parent(root2, root2.left.left))
  24. if __name__ == '__main__':
  25. app()

输出:

  1. _________0-9_________________
  2. / \
  3. _1-7_____ ________2-8_
  4. / \ / \
  5. 3-4 _4-6 __5-12__ 6-10_
  6. / / \ \
  7. 9-0 11-3 12-11 14-2
  8. None
  9. -
  10. ______________0-1_
  11. / \
  12. 1-2_____ 2-3
  13. \
  14. _4-4_
  15. / \
  16. 9-5 10-6
  17. --
  18. ______1
  19. / \
  20. 2__ 3
  21. \
  22. 4
  23. / \
  24. 5 6
  25. ---
  26. ______1
  27. / \
  28. _2__ 3
  29. / \
  30. 15 4
  31. / \
  32. 5 6
  33. ----
  34. ______1
  35. / \
  36. _2__ 3___
  37. / \ \
  38. 15 4 _2__
  39. / \ / \
  40. 5 6 15 4
  41. / \
  42. 5 6
  43. -----
  44. 1__
  45. / \
  46. 2 3
  47. / /
  48. 4 5
  49. ------
  50. 2
  51. /
  52. 4

相关文章