Last active
January 11, 2017 02:02
-
-
Save drem-darios/2b6b29a3a50bcc065466a504aa3c59a7 to your computer and use it in GitHub Desktop.
In 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 in_order_recursive(input, index): | |
if index >= len(input) or input[index] == None: | |
return | |
in_order_recursive(input, (index * 2) + 1) | |
print input[index], | |
in_order_recursive(input, (index * 2) + 2) | |
in_order_recursive([3,2,1,1,1,1,0,1,0], 0) | |
# 1 1 0 2 1 3 1 1 0 | |
def in_order(input): | |
parent_stack = [] | |
current = 0 | |
parent_stack.append(current) | |
while len(parent_stack) > 0: | |
left = (current * 2) + 1 | |
if left < len(input) and input[left] is not None: | |
parent_stack.append(current) | |
current = left | |
else: | |
print input[current], | |
current = parent_stack.pop() | |
right = (current * 2) + 2 | |
if right < len(input) and input[right] is not None: | |
if len(parent_stack) > 0: | |
print input[current], | |
current = right | |
in_order([3,2,1,1,1,1,0,1,0]) | |
# 1 1 0 2 1 3 1 1 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment