Created
December 19, 2011 17:44
-
-
Save abhin4v/1498119 to your computer and use it in GitHub Desktop.
Reconstruct a binary tree from its pre and post order traversals
This file contains hidden or 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
| data Tree a = NullNode | Node a (Tree a) (Tree a) | |
| instance (Show a) => Show (Tree a) where | |
| show NullNode = "" | |
| show (Node x NullNode NullNode) = show x | |
| show (Node x l r) = show x ++ "(" ++ show l ++ " " ++ show r ++ ")" | |
| preOrder :: Tree a -> [a] | |
| preOrder NullNode = [] | |
| preOrder (Node x l r) = x : (preOrder l ++ preOrder r) | |
| postOrder :: Tree a -> [a] | |
| postOrder NullNode = [] | |
| postOrder (Node x l r) = postOrder l ++ postOrder r ++ [x] | |
| inOrder :: Tree a -> [a] | |
| inOrder NullNode = [] | |
| inOrder (Node x l r) = inOrder l ++ [x] ++ inOrder r | |
| reconstruct :: (Eq a) => [a] -> [a] -> Tree a | |
| reconstruct pre post | |
| | length pre == 1 = Node (head pre) NullNode NullNode | |
| | otherwise = Node (head pre) left right | |
| where leftRoot = head . tail $ pre | |
| rightRoot = last . init $ post | |
| leftPre = takeWhile (/= rightRoot) . tail $ pre | |
| rightPre = dropWhile (/= rightRoot) . tail $ pre | |
| leftPost = takeWhile (/= leftRoot) (init post) ++ [leftRoot] | |
| rightPost = tail . dropWhile (/= leftRoot) . init $ post | |
| left = reconstruct leftPre leftPost | |
| right = reconstruct rightPre rightPost | |
| -- Main> reconstruct "iqjhlemvotsbrgyzkca&fpnudwx" "hemljvqsgyrzbtcpudnfw&xakoi" | |
| -- 'i'('q'('j'('h' 'l'('e' 'm')) 'v') 'o'('t'('s' 'b'('r'('g' 'y') 'z')) 'k'('c' 'a'('&'('f'('p' 'n'('u' 'd')) 'w') 'x')))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment