序列化二叉树(模拟)

题目来源https://www.acwing.com/problem/content/31/

 思路:

题目意思是让你通过给定的二叉树自定义生成一段字符串,再用这个字符串重新解析成二叉树。

序列化使用先序遍历,遇到空节点添加"null ",其他节点用to_string转为字符串即可。

反序列化从左往右遍历字符串,还是用先序遍历的方式建树,利用空格把节点分隔开,将字符串转化为数字。

如果是空节点,判断该字符是’n',返回即可。u记录当前字符,pos记录当前字符串数字后面的空格位置。

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

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string str;
        if(root==NULL){str+="null ";return str;}
        str+=to_string(root->val)+" ";
        str+=serialize(root->left);
        str+=serialize(root->right);
        return str;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        int u=0;
        return dfs_d(data,u);//
    }
    TreeNode* dfs_d(string data,int &u){
        int pos=u;
        while(data[pos]!=' ')pos++;
        if(data[u]=='n'){
            u=pos+1;
            return NULL;
        }
        int val=0;
        if(data[u]=='-'){
            for(int i=u+1;i<pos;i++){
                val=val*10+data[i]-'0';
            }
            val=-val;
        }
        else{
            for(int i=u;i<pos;i++){
                val=val*10+data[i]-'0';
            }
        }
        u=pos+1;
        auto root=new TreeNode(val);
        root->left=dfs_d(data,u);
        root->right=dfs_d(data,u);
        return root;
    }
};
原文地址:https://www.cnblogs.com/mohari/p/13756964.html