Last active
January 11, 2017 02:01
-
-
Save drem-darios/eb55497ca59401009cb439f092e6f3e5 to your computer and use it in GitHub Desktop.
Pre order traversal of a tree
This file contains 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 pre_order_recursive(input, index): | |
if index >= len(input) or input[index] == None: | |
return | |
print input[index], | |
pre_order_recursive(input, (index * 2) + 1) | |
pre_order_recursive(input, (index * 2) + 2) | |
pre_order_recursive([3,2,1,1,1,1,0,1,0], 0) | |
# 3 2 1 1 0 1 1 1 0 | |
def pre_order(input): | |
stack = [] | |
if input is None: | |
return | |
stack.append(0) | |
while len(stack) > 0: | |
current = stack.pop() | |
print input[current], | |
left = (current * 2) + 1 | |
right = (current * 2) + 2 | |
if right < len(input) and input[right] != None: | |
stack.append(right) | |
if left < len(input) and input[left] != None: | |
stack.append(left) | |
pre_order([3,2,1,1,1,1,0,1,0]) | |
# 3 2 1 1 0 1 1 1 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment