标签:private void 通过 存储 建立 har 符号表 builder node
这道题会先调序列化函数,然后再根据序列化生成的结果调用反序列化函数,最后和原始输入来对比,所以使用哪种遍历方式都可以,在这里我们使用前序遍历,因为这样序列化得到的结果,最开始就是树的根节点。
C++使用vector来存储节点的值,空指针使用0xFFFFFFFF来表示,在反序列化时遇到0xFFFFFFFF,就可以直接跳过了。
C++
class Solution { public: char* Serialize(TreeNode *root) { Dlr(root); int *res = new int[a.size()]; for(int i = 0;i < a.size(); i++) res[i] = a[i]; return (char*)res; } TreeNode* Deserialize(char *str) { int *p = (int*) str; return helper(p); } TreeNode* helper(int *&str) { if(*str == 0xFFFFFFFF){ str++; return nullptr; } TreeNode* res = new TreeNode(*str); str++; res->left = helper(str); res->right = helper(str); return res; } void Dlr(TreeNode *root){ if(root == nullptr){ a.push_back(0xFFFFFFFF); return; } a.push_back(root->val); Dlr(root->left); Dlr(root->right); } private: vector<int> a; };
Java
public class Solution { String Serialize(TreeNode root) { if(root == null) return ""; StringBuilder sb = new StringBuilder(); SerializeHelper(root); return string.toString(); } void SerializeHelper(TreeNode root) { if(root == null) { string.append("#,"); return; } string.append(root.val); string.append(‘,‘); SerializeHelper(root.left); SerializeHelper(root.right); } TreeNode Deserialize(String str) { if(str.length() == 0) return null; String[] strs = str.split(","); return DeserializeHelper(strs); } TreeNode DeserializeHelper(String[] strs) { if(strs[index].equals("#")){ index++; return null; } TreeNode root = new TreeNode(Integer.parseInt(strs[index])); index++; root.left = DeserializeHelper(strs); root.right = DeserializeHelper(strs); return root; } private StringBuilder string = new StringBuilder(); private int index = 0; }
标签:private void 通过 存储 建立 har 符号表 builder node
原文地址:https://www.cnblogs.com/silentteller/p/12115563.html