Last active
April 2, 2020 07:49
-
-
Save nhudinhtuan/e0927587d82f629a7b889994d18f5101 to your computer and use it in GitHub Desktop.
Tree traversal - preorder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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