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

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include <stringstream>

class Codec {
public:
    void serialize(TreeNode* root, stringstream& ss)
    {
        if(root==NULL)
        {
            ss<<"*";
            return ;
        }
        
        ss<<"n"<<root->val;
        serialize(root->left,  ss);
        serialize(root->right,  ss);
    }
    
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        stringstream ss;
        serialize(root, ss);
        return ss.str();
    }

    TreeNode* build(stringstream &ss)
    {
        char ch;
        TreeNode *r;
        ss>>ch;
        if(ch=='*')
        {
            return NULL;
        }
        else if(ch=='n')
        {
            int x;
            ss>>x;
            r = new TreeNode(x);
            r->left = build(ss);
            r->right= build(ss);
        }
        return r;
    }
    
    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        stringstream ss(data);
        return build(ss);
    }
};

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

猜你喜欢

转载自www.cnblogs.com/randyniu/p/9228160.html