2022-5-11 每日一题-leetcode
题目链接:https://leetcode.cn/problems/serialize-and-deserialize-bst/
个人题解:前序遍历+递归
代码:
class Codec {
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) 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 str) {
vector<int> data;
stringstream ssin(str);
int x, u = 0;
while(ssin>>x) data.push_back(x);
return dfs_d(data,u,INT_MIN,INT_MAX);
}
TreeNode* dfs_d(vector<int>& data, int& u, int minv, int maxv) {
if (u == data.size() || data[u] < minv || data[u] > maxv) return NULL;
auto root = new TreeNode(data[u ++ ]);
root->left = dfs_d(data, u, minv, root->val);
root->right = dfs_d(data, u, root->val + 1, maxv);
return root;
}
};
运行截图:


浙公网安备 33010602011771号