Leetcode-Serialize and Deserialize Binary Tree

解题思路:

利用先序遍历递归遍历二叉树,对于空节点也将其作为一个节点看待,这样序列化的二叉树可以看成是一个完全二叉树。

反序列化的时候,递归解析字符串,根据 根节点--左子树--右子树的规则构造二叉树。


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Codec {
public:

   void serialize(TreeNode* root,ostringstream& out)
   {
          if(root==NULL)
          {
          	out<<"# ";
          	return;
          }
          else
          {
            out<val<<" ";
            serialize(root->left,out);
            serialize(root->right,out);  
          }
   }
   
   TreeNode* deserialize(istringstream& in)
   {
   	    string val;
   	    in>>val;
   	    if(val=="#")return NULL;
   	    TreeNode* root = new TreeNode(stoi(val));
   	     root->left = deserialize(in);
   	    root->right = deserialize(in);
   	    return root;
   } 
   
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
       ostringstream out;
       serialize(root,out);
       return out.str();

    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        istringstream in(data);
        return deserialize(in);
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));


你可能感兴趣的:(C++,Leetcode)