Serializing and deserializing the binary tree?

Can anyone tell me how to serialize and deserialize the binary tree, there can also be duplicate elements in the tree. remember it is a general binary tree not a BST.

@vijju123 @kauts_kanu

you can follow this link:

link text

@sudip_95

I have seen that man, can you justify how that approach will handle duplicate elements in the tree.

I think @sudip_95 link should work. To handle duplicates you can store pairs like(element, frequecy) instead of storing only elements? I think that should work!

For perfect BST I was thinking below solution. But this would be bad solution space wise for general tree in worst case because of lot of -1.

You can make a simple array where 0^{th} element is root and 2*i and 2 * i+1 are left and right children, and i/2 would be parent of any node. You can easily handle duplicate elements by making a pair like (element, frequency) instead of single element, and when there is no element if left or right part of tree you can store -1 (or anything that would not be part of tree data).

1 Like

@kauts_kanu

I have failed to answer this question two times in interview, can you please explain in more details step by step.

@kauts_kanu ??

//