AcWing 50. 序列化二叉树
原题链接
困难
作者:
Baymax0211
,
2019-04-13 16:54:27
,
所有人可见
,
阅读 1082
算法1
(按照前序遍历来序列化与反序列化二叉树) $O(n^2)$
C++ 代码
//参考yxc
/**
* 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:
string serialize(TreeNode* root) {
string res;
//if (!root) return res;
dfs_s(root, res);
return res;
}
void dfs_s(TreeNode* root, string & res) {
if (!root) {
res += "null ";//这个是null加空格。。。。
return;
}
res += to_string(root->val) + ' ';
dfs_s(root->left, res);
dfs_s(root->right, res);
}
TreeNode* deserialize(string data) {
int u = 0;
return dfs_d(data, u);
}
TreeNode * dfs_d(string data, int &u) {
if(u == data.size()) return NULL;
int k = u ;
while(data[k] != ' ') k++;
if (data[u] == 'n') {
u = k + 1;
return NULL;
}
int sum = 0;
for (int i = u; i < k; i ++) {
sum = sum * 10 + data[i] - '0';
}
u = k + 1;
auto root = new TreeNode(sum);
root->left = dfs_d(data, u);
root->right = dfs_d(data, u);
return root;
}
};
对!好像是因为新加入了负数 然后我按照yxc的做法会wrong answer!现在应该加入负数判断才对
int sum = 0;
for (int i = u; i < k; i ++) {
sum = sum * 10 + data[i] - ‘0’;
}
测试数据中出现了负数,这里是不是要加入负数判断呀?