leetcode 297. 二叉树的序列化与反序列化

leetcode 297. 二叉树的序列化与反序列化_第1张图片

		/**
 * 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:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string res;
        dfs1(root,res);
        return res;
    }
    void dfs1(TreeNode*root,string &res)//传引用减少复制机制
    {
      if(!root)
      {
        res+="#,";
        return;
      }
      res+=to_string(root->val)+',';
      dfs1(root->left,res);
      dfs1(root->right,res);
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
      int u=0;
      return dfs2(data,u);  
    }
    TreeNode * dfs2(string &data, int &u)
    {
      if(data[u]=='#')
      {
        u+=2;//跳过,
        return nullptr;
      }
      
      int t=0;//记录数值
      bool is_minus=false;//判断正负
      if(data[u]=='-')
      {
        u++;//跳过-号
        is_minus=true;
      }
      while(data[u]!=',')
      {
        
        t=t*10+data[u]-'0';//还原数据
        u++;
      }
      u++;//跳过当前,
      if(is_minus)t=-t;//如果为-,则为-t
      TreeNode*root=new TreeNode(t);
      root->left=dfs2(data,u);//因为是按先序遍历的所以直接还原,
      root->right=dfs2(data,u);
      
      return root; 
      
    }
};

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

你可能感兴趣的:(树,leetcode,297.,二叉树的序列化与反序列化)