Amazon Interview Question
Software Engineer / DevelopersTeam: Development
Country: India
Interview Type: In-Person
We have to store two traversal one of the following
1> inorder, preorder
2> inorder, postorder
File is sequential storage of data, So we have to check how we could implement a binary tree in array.
If my parent is at location n then left child = 2n + 1 and left child = 2n+2
0 1 2 3 4 5 6 7 8 9
0 is root of the tree,
left child of 0 is at location : 2*0 + 1 = 1
right child of 0 is at location : 2*0 + 2 = 2 and so on.
For reconstruction we need to remember one more thing parent = n/2 location if child is at n.
Storing the tree nodes in preorder is sufficient. Given the node values (in preorder), the first value is root of subtree, value next to root is left child and the next value greater than root is right child. Do this recursively and you'll create the tree.
We can store the tree in follwoing format
- Santosh Diwase March 02, 2012(Node, leftSubtrre, rightSubtree) where subtree will be again in format of (Node, leftSubtree, rightSubtree).
e.g.
(10,(5, null,null),(15,(12, null, null),null))