由先序遍历和中序遍历序列建立二叉树(C语言实现)


/*
代码参考文章:
https://blog.csdn.net/weixin_43891802/article/details/118859860
思路参考文章:
https://blog.csdn.net/qq_39445165/article/details/91351856
思路:
主要的难点就在CreateBiTree函数这边

1)先序遍历中第一个是根那么在中序遍历中找到根那么左右子树就确定了,所以自然左右子树的范围就确定了,所以在递归方法中先序遍历的左子树的边界范围是l1 + 1, l1 + i - l2。
因为第一个是根所以下一次递归的时候应该是下一个位置,但是左子树应该在什么位置结束呢?我们可以通过中序遍历中左子树的范围进行确定,可以结合上面的例子进行理解,可以知道左子树的范围为l1 + (i - l2)。
也可以这样想设先序遍历左子树结束位置为x,则x + 1- (l1 + 1) = i - l2,所以可以得到左子树的结束范围是 l1 + (i - l2),对于中序遍历序列中当前左子树的范围应该是l2, i - 1(i为根所在的位置)。

2)对于右子树来说,我们知道先序遍历的范围的起点应该是在先序遍历左子树结束位置上加1的位置,结束位置是在r1, 中序遍历中右子树的范围应该是i + 1, r2
我们可以模仿之前的递归创建完全二叉树的例子,可以将根节点的左指针指向递归创建的左子树,根节点的右指针指向递归创建的右子树即可。

*/
#include #include #include typedef struct BiTNode { char ch; struct BiTNode *LChild; struct BiTNode *RChild; }BiTNode, *BiTree;
//建树 int pos = 0; BiTree CreateBiTree(char *str1, char *str2, int start, int end) { if(start<=end) { int i; BiTree T; T = (BiTNode *)malloc(sizeof(BiTNode)); T->ch = str1[pos]; for(i=start;i<=end;i++) if(str2[i] == str1[pos]) break; pos++; T->LChild = CreateBiTree(str1, str2, start, i-1); T->RChild = CreateBiTree(str1, str2, i+1, end); return T; } return NULL; } //Visit the Tree 后序遍历输出 void Visit(BiTree &T) { if(T != NULL) { Visit(T->LChild); Visit(T->RChild); printf("%c",T->ch); } } int main() { BiTree T; char str1[100], str2[100]; scanf("%s%s",str1, str2); int StrLength = strlen(str1); T = CreateBiTree(str1,str2,0,StrLength-1); Visit(T); return 0; }

相关