Thursday 8 September 2011

Serialize and deserialize a binary tree

Writing the tree to a file is called ‘serialization’ and reading back from the file to reconstruct the exact same binary tree is ‘deserialization’.To serialize a binary tree  we need to store information  of inorder and one of preoder/postorder traversals in arrays and transfer the data . De-serialization can be done using inorder and preorder data. If the tree is a Binary Search Tree then we  need only  preorder /postorder.

Following is the code to create a binary tree from inorder and preorder traversals.I have not tested it, there may be typos.

struct TreeNode
{
  struct TreeNode* left;
  struct TreeNode* right;
  int  elem;
};
TreeNode* BinaryTreeFromOrderings(int* inorder, int* preorder, int length)
{
  if(length == 0)
    {
      return NULL;
    }
  //We have root then;
  TreeNode* node = new TreeNode;
  node->elem = *inorder;
  int rootIndex = 0;
  for(;rootIndex < length; rootIndex++)
    {
      if(inorder[rootIndex] == *inorder)
        {
           break;
        }
    }
  //Left
  node->left = BinaryTreeFromOrderings(inorder+1, preorder, rootIndex);
  //Right
  node->right = BinaryTreeFromOrderings(inorder + rootIndex + 1, preorder + rootIndex + 1, length - (rootIndex + 1));
  return node;
}





No comments:

Post a Comment