Created
July 5, 2016 06:27
-
-
Save subramaniank/a91678181504e0bf30504a7943d33f49 to your computer and use it in GitHub Desktop.
Print preorder traversal of a tree given its inorder and postorder traversals
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 search(inorder, instart, inend, key): | |
for i in range(instart, inend+1): | |
if inorder[i] == key: | |
return i | |
return None | |
def printPre(inorder, postorder, instart, inend, poststart, postend): | |
if instart > inend or poststart > postend: | |
return None | |
print postorder[postend], | |
k = search(inorder, instart, inend, postorder[postend]) | |
printPre(inorder, postorder, | |
instart, k-1, | |
poststart, poststart + k - instart - 1) | |
printPre(inorder, postorder, | |
k+1, inend, | |
poststart + k - instart, postend-1) | |
inorderarr = [1,2,3,4,5,6,7,8,9,10,11,12] | |
postorderarr = [1,2,4,3,7,6,5,10,12,11,9,8] | |
printPre(inorderarr, postorderarr, 0, 11, 0, 11) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment