struct Node { //树节点结构体
Node* lchild;
Node* rchild;
int val;
}Tree[50]; //静态内存分配数组
int loc; //数组中已分配节点个数
Node* creat() { //申请一个节点空间
Tree[loc].lchild = Tree[loc].rchild = NULL;
return &Tree[loc++]; //返回指针且loc增加
}
int str1[30], str2[30]; //保存前序和中序结果
Node* build(int s1,int e1,int s2, int e2){ //还原树
Node* ret = creat(); //为树根节点申请空间
ret->val = str1[s1];
int rootx;
for (int i = s2; i <= e2; i++) {
if (str2[i] == str1[s1]) { //查找该根节点字符在中序序列位置
rootx = i;
break;
}
}
if (rootx != s2) {
ret->lchild = build(s1 + 1, s1 + (rootx - s2), s2, rootx - 1); //递归还原左子树
}
if (rootx != e2) {
ret->rchild = build(s1 + (rootx - s2) + 1, e1, rootx + 1, e2); //递归还原右子树
}
return ret;
}
C++ 由前序和中序重建二叉树
最新推荐文章于 2022-11-08 01:00:11 发布