BST二叉搜索树插入一个节点后检测距离当前节点最近的失衡点,binarytree,Python

x33g5p2x  于2021-11-28 转载在 Python  
字(0.7k)|赞(0)|评价(0)|浏览(339)

BST二叉搜索树插入一个节点后检测距离当前节点最近的失衡点,binarytree,Python

思路:二叉搜索树之所以不平衡,发生在插入新节点后,那么沿着新插入节点,逆向沿着当前节点的父节点,一路检测节点平衡因子,当发现绝对值>1的平衡因子,即为最近的失衡点。

  1. def check_unblance(root, number):
  2. ret = None
  3. un_blance_node = None
  4. for n in root.levelorder:
  5. if n.value == number:
  6. un_blance_node = n
  7. break
  8. h = 0
  9. while h <= root.height:
  10. h = h + 1
  11. factor = get_blance_factor(un_blance_node)
  12. print('节点', un_blance_node.value, '平衡因子', factor)
  13. if abs(factor) > 1:
  14. print('检测到不平衡', un_blance_node.value, factor)
  15. ret = (un_blance_node, factor)
  16. break
  17. else:
  18. un_blance_node = get_parent(root, un_blance_node)
  19. return ret
  20. def get_blance_factor(node):
  21. factor = 0
  22. if node.height == 0:
  23. factor = 0
  24. return factor
  25. left = node.left
  26. right = node.right
  27. lh = 0
  28. rh = 0
  29. if left is not None:
  30. lh = node.left.height + 1
  31. if right is not None:
  32. rh = node.right.height + 1
  33. factor = lh - rh
  34. return factor

最后返回(失衡节点,平衡因子)。

相关文章