搜索二叉树的序列化和反序列化
原题在这里:
概述题意,要求将给定二叉树根节点转化为字符串,根据自己字符串结构转换还原二叉树。
这里二叉树为搜索二叉树。
analyse:
普通前序遍历转换为string,普通前序构造node。
虽然思路很简单,也是前面做过类似的题,但是这次解法优于上次不少。
这里的代码也能ac上次的题。
struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} };
code:
class Codec { string s; int i; public: // Encodes a tree to a single string. string serialize(TreeNode *root) { if (!root) return "x"; return to_string(root->val) + " " + serialize(root->left) + " " + serialize(root->right); } string get() { string x; while (i < s.length() && s[i] != ' ') x += s[i++]; ++i; return x; } // Decodes your encoded data to tree. TreeNode *make() { if (i >= s.length()) return nullptr; string x = get(); if (x == "x") return nullptr; // cout << "数据化:" << x << endl; TreeNode *now = new TreeNode(stoi(x)); now->left = make(); now->right = make(); return now; } TreeNode *deserialize(string data) { //递归构造 s = data; i = 0; return make(); } };
【Over】

浙公网安备 33010602011771号