请实现两个函数,分别用来序列化和反序列化二叉树

// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
//

include "stdafx.h"

include "stdafx.h"

include

include

include

include

include

include

include

include

include

include<forward_list>

using namespace std;

struct TreeNode {
unsigned char val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};

class Solution {
public:
char* Serialize(TreeNode *root) {
getData(root);

vec.push_back('\0'); //char遇到'\0'结束运行 //此句非常重要
char *ch = &vec[0];
return ch;
}

vector< char> vec;
void getData(TreeNode *T)
{
if (T == NULL)
{
vec.push_back('#');
return;
}
vec.push_back(T->val);
getData(T->left);
getData(T->right);
}

int p = -1;
TreeNode* Deserialize(char *str) {
if (str == NULL) return NULL;
++p;
if (str[p] == '#') return NULL;
TreeNode *T = new TreeNode(str[p]);
T->left = Deserialize(str);
T->right = Deserialize(str);
return T;
}

void preOrder(TreeNode *T)
{
if (T == NULL) return;
cout << T->val << " ";
preOrder(T->left);
preOrder(T->right);
}
};

int main()
{

Solution so;
TreeNode *T;
char *str = "124###3##";

T=so.Deserialize(str);
cout << "前序遍历结果是:" << endl;
so.preOrder(T);
//so.getData(T);
//cout << "qu 队列中的值:" << endl;
//so.print();
cout << endl;
char *ch = so.Serialize(T);

cout << "ch的长度:" << strlen(ch) << endl;

return 0;
}

//注意:此程序有问题,不能通过100%的测试用例,因为char类型表示的范围,只能是-128--127

posted @ 2016-10-26 17:06  wdan2016  阅读(1136)  评论(0)    收藏  举报