面试题62 序列化二叉树
题目描述
请实现两个函数,分别用来序列化和反序列化二叉树
1 /* 2 struct TreeNode { 3 int val; 4 struct TreeNode *left; 5 struct TreeNode *right; 6 TreeNode(int x) : 7 val(x), left(NULL), right(NULL) { 8 } 9 }; 10 */ 11 typedef TreeNode node; 12 typedef TreeNode* pnode; 13 typedef int* pint; 14 class Solution { 15 vector<int> buf; 16 void dfs(pnode p){ 17 if(!p) buf.push_back(0x23333); 18 else{ 19 buf.push_back(p -> val); 20 dfs(p -> left); 21 dfs(p -> right); 22 } 23 } 24 pnode dfs2(pint& p){ 25 if(*p == 0x23333){ 26 ++p; 27 return NULL; 28 } 29 pnode res = new node(*p); 30 ++p; 31 res -> left = dfs2(p); 32 res -> right = dfs2(p); 33 return res; 34 } 35 public: 36 char* Serialize(TreeNode *p) { 37 buf.clear(); 38 dfs(p); 39 int *res = new int[buf.size()]; 40 for(unsigned int i = 0; i < buf.size(); ++i) res[i] = buf[i]; 41 return (char*)res; 42 } 43 TreeNode* Deserialize(char *str) { 44 int *p = (int*)str; 45 return dfs2(p); 46 } 47 };