Skip to content

Instantly share code, notes, and snippets.

@vigack
Last active December 17, 2017 17:10
Show Gist options
  • Save vigack/9484684325c668e850d55692be71b22a to your computer and use it in GitHub Desktop.
Save vigack/9484684325c668e850d55692be71b22a to your computer and use it in GitHub Desktop.
tree traversal without recursion
"""
class Node:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
"""
def preOrder(root):
pass
def postOrder(root):
stack = []
curr = root
while curr :
stack.append(curr)
if curr.right:
stack.append(curr.right)
if curr.left:
stack.append(curr.left)
stack.reverse()
print(' '.join(map, stack))
def inOrder(root):
stack = []
res = []
curr = root
while curr or stack :
if not curr :
tmp = stack.pop()
res.append(tmp.data)
curr = tmp.right
continue
stack.append(curr)
curr = curr.left
print(' '.join(map(str, res)))
# 按层遍历
def levelOrder(root):
queue = [root]
res = []
while queue:
curr = queue.pop(0)
res.append(curr.data)
if curr.left:
queue.append(curr.left)
if curr.right:
queue.append(curr.right)
print(' '.join(map(str, res)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment