二叉搜索树BST广度优先搜索遍历BFS计算树高度,非递归,binarytree,python

x33g5p2x  于2021-11-20 转载在 Python  
字(1.0k)|赞(0)|评价(0)|浏览(490)

二叉搜索树BST广度优先搜索遍历BFS计算树高度,非递归,binarytree,python

基本原理:首先对二叉树搜索树进行BFS广度优先搜索遍历,搜索遍历后的节点访问依次顺序的存放在数组中,那么此时数组中最后一个节点,即是树中距离根最远的节点。然后用这个节点逆向的沿着父节点一层一层的往上爬,每爬一层就计数为1,直到根节点没有了父节点为止,算法结束。最终累计的计数即为树的高度。也就是说,广度遍历搜索是一种层次推进的搜索遍历,具体在BST二叉树搜索树中,一层代表数的高度1,对层高计数,即为该树的高度。

  1. from binarytree import bst, get_parent
  2. def app():
  3. t = bst(height=0, is_perfect=False)
  4. print(t)
  5. print('标准API获得的树高', t.height)
  6. print('-----')
  7. h = get_tree_height(t)
  8. print('广度遍历思想求得树高', h)
  9. def get_tree_height(node):
  10. most_far_edge_node = node.levelorder.pop()
  11. print('most_far_edge_node', most_far_edge_node.value)
  12. tree_height = 0
  13. while True:
  14. print('-')
  15. p = get_parent(node, most_far_edge_node)
  16. if p is not None:
  17. print('parent', most_far_edge_node.value, '->', p.value)
  18. tree_height = tree_height + 1
  19. most_far_edge_node = p
  20. else:
  21. break
  22. return tree_height
  23. if __name__ == '__main__':
  24. app()

输出:

  1. 0________
  2. \
  3. ______5__________________
  4. / \
  5. 1__ _______57_________
  6. \ / \
  7. 3 ____47 ____62
  8. / \ / \ /
  9. 2 4 _23 48 _60
  10. / \ \ / \
  11. 20 35 56 58 61
  12. 标准API获得的树高 5
  13. -----
  14. most_far_edge_node 61
  15. -
  16. parent 61 -> 60
  17. -
  18. parent 60 -> 62
  19. -
  20. parent 62 -> 57
  21. -
  22. parent 57 -> 5
  23. -
  24. parent 5 -> 0
  25. -
  26. 广度遍历思想求得树高 5

相关文章