针对测试用例有负数的新的题解
blablabla
样例
/**
* 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 res;
Pre(root, res);
return res;
}
void Pre(TreeNode* root, string &res)
{
if(!root)
{
res += "null ";
return;
}
res += to_string(root->val) + ' ';
Pre(root->left, res);
Pre(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 NULL;
}
int k = u;
while (data[k] != ' ')
{
k++;
}
if(data[u] == 'n')
{
u = k + 1;
return NULL;
}
int val = 0;
for(int i = u; i < k; i++)
{
if(data[i] == '-')
{
i++;
val = val * 10 + data[i] - '0';
}
else
{
val = val * 10 + data[i] - '0';
}
}
if(data[u] == '-')
{
val = 0 - val;
}
u = k + 1;
auto root = new TreeNode(val);
root->left = dfs_d(data, u);
root->right = dfs_d(data, u);
return root;
}
};
算法1
(暴力枚举) $O(n^2)$
blablabla
时间复杂度分析:blablabla
C++ 代码
blablabla
算法2
(暴力枚举) $O(n^2)$
blablabla
时间复杂度分析:blablabla
C++ 代码
blablabla