Thursday, April 18, 2013

serialization/deserialization of a binary tree(C++ code)

Leetcode Serialization/Deserialization of a Binary Tree

Design an algorithm and write code to 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’.

Assume we have a binary tree below:
    _30_ 
   /    \    
  10    20
 /     /  \ 
50    45  35
Using pre-order traversal, the algorithm should write the following to a file:
30 10 50 # # # 20 45 # # 35 # #

这个OJ没有,当面试题准备做做。
  1. void writeBinaryTree(TreeNode *p, ostream &out) {  
  2.   
  3.   if(!p) {out<<"# "return;}  
  4.   
  5.   out<<p->val<<" ";  
  6.   
  7.   writeBinaryTree(p->left, out);  
  8.   
  9.   writeBinaryTree(p->right, out);  
  10.   
  11. }   
 
  1. void readBinaryTree(TreeNode *&p, ifstream &fin){  
  2.   
  3.   if(fin.eof()) return;  
  4.   
  5.   string value;  
  6.   
  7.   value<<fin;  
  8.   
  9.   int number ;  
  10.   
  11.   if( istringstream(value)>>number){  
  12.   
  13.   p = new TreeNode(number);  
  14.   
  15.   readBinaryTree(p->left, fin);  
  16.   
  17.   readBinaryTree(p->right,fin);  
  18.   
  19.   }  
  20.   
  21. }   


No comments:

Post a Comment