Skip to content

Instantly share code, notes, and snippets.

@whiledoing
Created June 9, 2018 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whiledoing/eef4e3c080e967389a3844c8e71bb18a to your computer and use it in GitHub Desktop.
Save whiledoing/eef4e3c080e967389a3844c8e71bb18a to your computer and use it in GitHub Desktop.
[python-tree-travel-use-stack] #python #algorithm
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def front_travel(root):
if not root: return
s = [root]
while s:
cur = s.pop()
print(cur.val)
if cur.right:
s.append(cur.right)
if cur.left:
s.append(cur.left)
def mid_travel(root):
if not root: return
cur, s = root, []
while cur or s:
while cur:
s.append(cur)
cur = cur.left
cur = s.pop()
print(cur.val)
cur = cur.right
def post_travel(root):
if not root: return
s = [(0, root)]
while s:
seen, cur = s.pop()
if not cur: continue
if seen:
print(cur.val)
else:
s.append((1, cur))
s.append((0, cur.right))
s.append((0, cur.left))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment