tree_0.svg

堆栈实现

  1. def stack_print(root):
  2. stack = []
  3. result = []
  4. while root or stack:
  5. while root:
  6. stack.append(root)
  7. result.append(root.val)
  8. root = root.left
  9. if stack:
  10. root = stack.pop()
  11. root = root.right
  12. return result

递归实现

  1. def recursive_print(root):
  2. result = []
  3. def preorder(root):
  4. if not root:
  5. return
  6. result.append(root.val)
  7. preorder(root.left)
  8. preorder(root.right)
  9. preorder(root)
  10. return result

完整代码

  1. class BinTree(object):
  2. def __init__(self, root):
  3. self.root = root
  4. def stack_print(self, root):
  5. """堆栈实现"""
  6. stack = []
  7. while root or stack:
  8. while root:
  9. stack.append(root)
  10. print(root.val)
  11. root = root.left
  12. if stack:
  13. root = stack.pop()
  14. root = root.right
  15. def recursive_print(self, root):
  16. """递归实现"""
  17. if not root:
  18. return
  19. print(root.val)
  20. self.recursive_print(root.left)
  21. self.recursive_print(root.right)
  22. def main():
  23. left = TreeNode(2, left=TreeNode(4), right=TreeNode(5))
  24. right = TreeNode(3, left=TreeNode(6), right=TreeNode(7))
  25. root = TreeNode(1, left=left, right=right)
  26. tree = BinTree(root)
  27. print('递归 先序遍历:')
  28. tree.recursive_print(tree.root)
  29. print('堆栈 先序遍历:')
  30. tree.stack_print(tree.root)