题目描述
blablabla 加入了负数样本
样例
blablabla
算法1
(暴力枚举) $O(n^2)$
blablabla
时间复杂度分析:blablabla
C++ 代码
blablabla
算法2
(暴力枚举) $O(n^2)$
blablabla
时间复杂度分析:blablabla
C++ 代码
/**
* 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 {//是不是因为没有加入负数判断??对!yxc的做法没有加入负数判断!
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string res;
dfs_s(root, res);
return res;
}
void dfs_s(TreeNode *root, string &res){
if(!root){
res += "null ";
return;
}
res += to_string(root->val) + ' ';
dfs_s(root->left, res);
dfs_s(root->right, res);
}
// 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){
if(u == data.size()) return nullptr;
int k = u;
while (data[k] != ' ') k ++ ;
if (data[u] == 'n'){
u = k + 1;
return nullptr;
}
int val = 0;
bool is_neg = false;
if(data[u] == '-') is_neg = true, u ++;
for(int i = u; i < k; i ++ ) val = val * 10 + data[i] - '0';
if(is_neg) val = - val;
u = k + 1;
auto root = new TreeNode(val);
root->left = dfs_d(data, u);
root->right = dfs_d(data, u);
return root;
}
};