C语言实现二叉树的重载:
通过二叉树的中序遍历顺序和前序(或后序)遍历顺序还原二叉树;
这里是前序和中序,通过递归实现。
typedef struct BTNode { // 孩子表示法
char data;
struct BTNode* lchild, *rchild;
}BTNode;
BTNode* CreateRoot(char c) {//生成根节点的函数
BTNode* tmp = (BTNode*)malloc(sizeof(BTNode));
if (!tmp) {
printf("申请空间失败,无法创建根节点\n");
}
else {
tmp->data = c;
tmp->lchild = NULL;
tmp->rchild = NULL;
}
return tmp;
}
BTNode* RestoreTree(char* ppos, char* ipos, int n) { // ppos是先序遍历顺序,ipos是中序遍历顺序;
if (strlen(ipos) == 0) {
return NULL; // 如果ipos长度为9,那么表明没有孩子,置为NULL;
}
static char* pppos = ppos; // 一个静态指针变量,指向先序遍历;
int i = 0, leftStrlen = 0, k = 0, rightStrlen = 0;
char left[100], right[100];
BTNode* root = CreateRoot(ppos[0]); // 先序的第一个值是根节点
while (ipos[i] != ppos[0]) {
left[leftStrlen++] = ipos[i]; // 把在中序顺序中,把根节点左边的顺序保存
i++;
}left[leftStrlen] = '\0';
while (++i<n){
right[rightStrlen++] = ipos[i]; // 把在中序顺序中,根节点右边的顺序保存,这样就做到把左右子树分开了,接下来递归就可以了。
}right[rightStrlen] = '\0';
if (strlen(left) == 0) root->lchild = RestoreTree(pppos, left, leftStrlen); // 如果左边的字符串为空,则没有左子树,指针不需要后移
else root->lchild = RestoreTree(++pppos, left, leftStrlen);
if (strlen(right) == 0) root->rchild = RestoreTree(pppos, right, rightStrlen);// 同理
else root->rchild = RestoreTree(++pppos,right, rightStrlen);
return root;
}