Efficient Array Storage for Binary Tree

后端 未结 5 797
暗喜
暗喜 2020-12-04 12:32

We have to write the nodes of a binary tree to a file. What is the most space efficient way of writing a binary tree . We can store it in array format with parent in positi

5条回答
  •  星月不相逢
    2020-12-04 12:59

    Think about XML. It's a kind of tree serialization. For example:

    
                                           1
                                               /   \
                                        2     3
                                             / \
                                                  4   5
            
            
        
    
    

    Then, why the spaces and tags ? We can omit them, step by step:

    <1>
       <2>
       <3>
         <4>
         <5>
       
    
    

    Remove the spaces: <1><2><3><4><5>.

    Remove the angle brackets: 12/34/5///

    Now the problem is: what if a node has a empty left subtree and non-empty right subtree? Then we can use another special charactor, '#' to represent an empty left sub-tree.

    For example:

        1
      /   \
          2
         /  \
        3
    

    This tree can be serialized as: 1#23///.

提交回复
热议问题