当前位置:   article > 正文

用python实现排序二叉树(中序)_python对树进行中序排序

python对树进行中序排序
  1. class SortTree():
  2. def __init__(self):
  3. self.root = None
  4. def add(self, item):
  5. node = Node(item)
  6. cur = self.root
  7. if cur == None:
  8. self.root = node
  9. return
  10. while cur:
  11. if item > cur.item:
  12. if cur.right == None:
  13. cur.right = node
  14. break
  15. else:
  16. cur = cur.right
  17. else:
  18. if cur.left == None:
  19. cur.left = node
  20. break
  21. else:
  22. cur = cur.left
  23. def travle(self):
  24. cur = self.root
  25. q = [cur]
  26. while q:
  27. nd = q.pop(0)
  28. print(nd.item)
  29. if nd.left:
  30. q.append(nd.left)
  31. if nd.right:
  32. q.append(nd.right)
  33. def middle(self, root):
  34. if root == None:
  35. return
  36. self.middle(root.left)
  37. print(root.item)
  38. self.middle(root.right)
  39. t = SortTree()
  40. alist = [3, 8, 5, 7, 6, 2, 9, 4, 1]
  41. for i in alist:
  42. t.add(i)
  43. # t.travle()
  44. t.middle(t.root)

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/993248
推荐阅读
相关标签
  

闽ICP备14008679号