struct Node* lchild, * rchild;
Node* p = (Node*)malloc(sizeof(Node));
p->lchild = p->rchild = NULL;
if (root == NULL) return getNewNode(key);
if (rand() % 2) root->lchild = insert(root->lchild, key);
else root->rchild = insert(root->rchild, key);
for (int i = 0; i < n; i++) root = insert(root, rand() & 100);
char str[1000]; //广义表信息存到str中
void __serialize(Node* root) {
if (root == NULL) return;
len += sprintf(str + len, "%d", root->key);
if (!root->lchild && !root->rchild) return;
len += sprintf(str + len, "(");
__serialize(root->lchild);
if (root->rchild) len += sprintf(str + len, ",");
__serialize(root->rchild);
len += sprintf(str + len, ")");
void serialize(Node* root) {
memset(str, 0, sizeof(str));
void output(Node* root) {
if (root == NULL) return;
root->lchild ? root->lchild->key : -1,
root->rchild ? root->rchild->key : -1);
Node** sta = (Node**)malloc(sizeof(Node*) * MAX);
int top = -1, flag = 0, scode = 0;
//flag表示当前节点该连在栈顶结点的左边还是右边
//scode为状态码,0:任务分发 遇到关键字赋为1 遇到左括号赋为2 遇到逗号赋为3 遇到右括号赋为4
Node* p = NULL, *root = NULL;
for (int i = 0; str[i]; i++) {
if (str[i] >= '0' && str[i] <= '9') scode = 1;
else if (str[i] == '(') scode = 2;
else if (str[i] == ',') scode = 3;
//分发了任务,没有处理当前字符,为了抵消for循环中的i++
while (str[i] <= '9' && str[i] >= '0') {
key = key * 10 + (str[i] - '0');
//flag为1,连在栈顶结点的左边;flag为2,连在栈顶结点的右边
if (top >= 0 && flag == 0) sta[top]->lchild = p;
if (top >= 0 && flag == 1) sta[top]->rchild = p;
//读入关键字后i指向关键字下一位,for循环后i会加1,那么关键字下一位就没有被处理
Node* root = getRandomBinaryTree(MAX);
output(root); printf("\n");
printf("str : %s\n\n", str);
Node* new_root = deserialize(str, len);