1

Recently I attended an interview and I was asked to serialize a given tree. As I was about to start, the interviewer asked about the approach to take. I replied, it's going to be preorder with some special char for null. He said, that will waste a lot of space -can you do that without storing extra chars? But all approach need extra space, I know a few :

  1. Inorder and preorder both rep.. but this needs 2n space upfront
  2. Level order .. but again this needs additional space
  3. Preoder with special char

But above approaches need additional space. He was adamant that we can do it without additional storage .. on asking what the approach could be .. he asked to google. Any clues? I have been googling and am not able to find any approach where null is not represented by special character.

cpandey05
  • 1,241
  • 2
  • 17
  • 30
  • It's going to require between 1 and 2 bits per node. What's in the nodes? You may be able to hide it in the other data. – Matt Timmermans Oct 02 '19 at 16:16
  • 1
    Maybe they meant something like [this idea](http://spencermortensen.com/articles/serialize-a-binary-tree-in-minimal-space/). – conditionalMethod Oct 02 '19 at 19:25
  • @MattTimmermans It was just and interview, and we got stuck there itself as can we do without wasting space or not! I proposed that we can save some additional info with node or may be use some bit info.. but any way it will need some space. – cpandey05 Oct 03 '19 at 13:30
  • Yes, the 'no extra space' needs to be qualified. If the representation of one node in the serialization is going to take space M and there are N nodes in the tree, then they can't be asking to serialize the tree in MN space. With that space you can only store 2^{MN} different codes, but there are N^{N-2} difference trees of N nodes. See [Cayley's formula](https://en.wikipedia.org/wiki/Cayley%27s_formula). – conditionalMethod Oct 03 '19 at 17:17

0 Answers0