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

本文介绍了一种二叉树的序列化和反序列化方法,使用深度优先搜索(DFS)策略,将二叉树转换为字符串并能从字符串中还原二叉树。该方法适用于树结构的数据持久化存储或网络传输。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

		/**
 * 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));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值