题解 | #序列化二叉树#
序列化二叉树
http://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84
通过前序遍历或层次遍历(递归 或 非递归)去建树
注意char* 的使用
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
char* Serialize(TreeNode *root) {
if(!root)
return NULL;
queue<TreeNode*> q;
int* s = new int[101];
int count = 0;
q.push(root);
while(!q.empty()){
TreeNode* temp = q.front();
if(temp)
s[count] = temp->val;
else
s[count] = -1;
count ++;
if(temp){
q.push(temp->left);
q.push(temp->right);
}
q.pop();
}
return (char*)s;
}
TreeNode* Deserialize(char *str) {
if(!str)
return NULL;
int* t = (int*)str;
TreeNode* root = new TreeNode(t[0]);
queue<TreeNode*> q;
int count = 1;
q.push(root);
while(!q.empty()){
TreeNode* temp = q.front();
if(t[count] != -1){
temp->left = new TreeNode(t[count]);
q.push(temp->left);
}
count ++;
if(t[count] != -1){
temp->right = new TreeNode(t[count]);
q.push(temp->right);
}
count ++;
q.pop();
}
return root;
}
};