Skip to content

Instantly share code, notes, and snippets.

@drem-darios
Last active January 11, 2017 02:02
Show Gist options
  • Save drem-darios/2b6b29a3a50bcc065466a504aa3c59a7 to your computer and use it in GitHub Desktop.
Save drem-darios/2b6b29a3a50bcc065466a504aa3c59a7 to your computer and use it in GitHub Desktop.
In order traversal of a tree
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