-
Notifications
You must be signed in to change notification settings - Fork 0
/
297.二叉树的序列化与反序列化.cpp
110 lines (95 loc) · 2.15 KB
/
297.二叉树的序列化与反序列化.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
* @lc app=leetcode.cn id=297 lang=cpp
*
* [297] 二叉树的序列化与反序列化
*/
// @lc code=start
/**
* Definition for a binary tree node.
* */
#include<iostream>
#include<vector>
#include<string>
#include<sstream>
using namespace std;
// 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) {
v.clear();
dfs(root);
string ans;
ans.push_back('[');
for(int i=0;i<v.size();i++)
{
ans+=v[i];
if(i!=v.size()-1)
{
ans+=",";
}
}
ans.push_back(']');
// cout<<ans<<endl;
return ans;
}
vector<string> v;
void dfs(TreeNode* root)
{
if(root==NULL)
{
v.push_back("#");
return;
}
stringstream ss;
ss<<root->val;
// cout<<ss.str()<<endl;
v.push_back(ss.str());
dfs(root->left);
dfs(root->right);
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
v.clear();
for(int i=1, front=0;i<data.size();i++)
{
if(data[i]==','||data[i]==']')
{
string s = data.substr(front+1, i-front-1);
// cout<<s<<endl;
v.push_back(s);
front = i;
}
}
int pos = 0;
TreeNode* root = rebuild(pos);
return root;
}
TreeNode* rebuild(int &pos)
{
if(v[pos]=="#")
{
return NULL;
}
stringstream ss(v[pos]);
int val = 0;
ss >> val;
// cout<<val<<endl;
TreeNode* root = new TreeNode(val);
if(root!=NULL)
{
root->left = rebuild(++pos);
root->right = rebuild(++pos);
}
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
// @lc code=end