Amazon Interview Question
Software Engineer / DevelopersThis is how I solved it during interview,
TO STORE INTO FILE:
Use BFS and store the values whenever there is no child, store 'null'
TO RECONSTRUCT:
Read all nodes into array.
For 'n'th node left child is at (2n+1)th position and right child is at (2n+2)th position.
If those positions are 'null' then node doesn't have children.
Storing inorder and postorder will destroy the structure of tree.
There was once problem asked in code jam 2009 on decision trees.
In that problem one decision tree was presented to user in form of file .
I think that would be better way to write a binary tree in file.
supppose tree is
2
1 3
And second tree is
1
2
3
having same preorder traversal.
So how you are going to reconstruct the tree.
But the inorder traversal is different. This question is asked in google interview also and it's a property of binary tree that you can always uniquely construct it back with pre-order and in-order traversla
How about?
1. Write BFS preorder, write the parent's offset to each node's section and the fact that it's left/right child. This can be done quite easily with recursion. This has to be done to preserve the tree structure.
2. When reading, read each node in order, construct the node, stick it into a hashtable (key=offset, value=pointer of node).
3. When reading a child node, look up the hashtable with the parent's offset, get the node * of the parent, construct and node, and relink it with the parent.
I can give idea to solve this problem
- solver November 25, 2010store the in-oder and post-order traversal output of binary tree in file
now with these two out we can reconstruct the same tree.