Skip to content

Instantly share code, notes, and snippets.

@jliu90
Last active August 29, 2015 14:02
Show Gist options
  • Save jliu90/ece03417a494911038bf to your computer and use it in GitHub Desktop.
Save jliu90/ece03417a494911038bf to your computer and use it in GitHub Desktop.
convert in-order and pre-order tree presentation to post-order
#test cases
in_order_1 = "ABCDEFG"
pre_order_1 = "DBACEGF"
post_order_1 = "ACBFGED"
in_order_2 = "CBAD"
pre_order_2 = "BCAD"
post_order_2 = "CDAB"
def convert(in_order, pre_order):
#get root node
root = pre_order[0]
#find corresponding in-order representation for left and right subtree
in_left = in_order[:in_order.find(root)]
in_right = in_order[in_order.find(root) + 1:]
#recursively invoke
left = convert(in_left, pre_order[1:len(in_left) + 1]) if in_left else ""
right = convert(in_right, pre_order[len(in_left) + 1:]) if in_right else ""
#return post order
return left + right + root
assert convert(in_order_1, pre_order_1) == post_order_1
assert convert(in_order_2, pre_order_2) == post_order_2
assert convert("ADEFGHMZ", "GDAFEMHZ") == "AEFDHZMG"
print "OK"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment