Skip to content

Instantly share code, notes, and snippets.

@nhudinhtuan
Last active April 2, 2020 07:49
Show Gist options
  • Save nhudinhtuan/e0927587d82f629a7b889994d18f5101 to your computer and use it in GitHub Desktop.
Save nhudinhtuan/e0927587d82f629a7b889994d18f5101 to your computer and use it in GitHub Desktop.
Tree traversal - preorder
def preorder_traversal_iterating(root):
if not root:
return []
result = []
# using stack
stack = [root]
while stack:
current = stack.pop()
# visit node
result.append(current.val)
# put right to stack first as we want to visit right after left!!
if current.right:
stack.append(current.right)
if current.left:
stack.append(current.left)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment