I recently came across an interview question asked by Amazon :
Given a binary tree to be passed through a network. How to pass this tree in minimum space?
Ok, my 2 approaches to above question are:
We can store the inorder of tree in an array along with preorder (or postorder or level-order) in another array and then pass the 2 arrays into the network. This consumes a lot of space. So rejecting it, I came up with other solution.
We will pass each node of the tree level-wise along with some information about it's left and right child.
Method 2
Additional Information along with nodes:
if left child==NULL && right child==NULL pass 00 along with node
if left child!=NULL && right child==NULL pass 10 along with node
if left child==NULL && right child!=NULL pass 01 along with node
if left child!=NULL && right child!=NULL pass 11 along with node
Let us look at an example for 2nd method
Level Wise
- Pass node(2) and 11
- Pass node(7) and 11
- Pass node(5) and 11
- Pass node(2) and 00
- Pass node(6) and 11
- Pass node(9) and 10
- Pass node(5) and 00
- Pass node(11) and 00
- Pass node(4) and 00
If I am correct, then in this way, you can do reconstruction of the tree on the other side of the network also by checking the additional information easily and (pardon me if I am wrong then) you are using less memory because you are only passing node's value and additional information at a time instead of passing the whole tree.
Ok, now I have 2 questions:
- Is my Method 2 correct or are there any exceptional cases for that which I may have missed.
- Is there any more efficient way other than the 2 described to send the tree onto the network?