二叉树的还原与遍历
2014-04-07 16:38
155 查看
由前序遍历串与中序遍历串还原二叉树,并得到二叉树的后序遍历串。
#include<stdio.h> #include<string.h> struct Node{ //树结点结构体 Node *lchild; Node *rchild; char c; }Tree[50]; int loc;//静态数组中已经分配的结点个数 Node *creat(){//申请一个结点空间,返回指向其的指针 Tree[loc].lchild = Tree[loc].rchild = NULL; return &Tree[loc++]; } void postOrder(Node * T){//后序遍历树 if(T->lchild != NULL) postOrder(T->lchild ); if(T->rchild != NULL) postOrder(T->rchild ); printf("%c",T->c ); } char str1[30],str2[30]; Node *build(int s1,int e1,int s2,int e2)//由前序和中序遍历结果还原二叉树 { Node *root = creat(); root->c = str1[s1]; int rootidx; for(int i=s2;i<=e2;i++) { if(str1[s1]==str2[i]) { rootidx = i; break; } } if(rootidx!=s2)//左子树不为空 { root->lchild = build(s1+1,s1+(rootidx-s2),s2,rootidx-1); } if(rootidx!=e2)//右子树不为空 { root->rchild = build(s1+(rootidx-s2)+1,e1,rootidx+1,e2); } return root; } int main() { while(scanf("%s",str1)!=EOF) { // getchar(); scanf("%s",str2); loc = 0; int l1 = strlen(str1); int l2 = strlen(str2); Node *T = build(0,l1-1,0,l2-1); postOrder(T); printf("\n"); } return 0; }
相关文章推荐
- 数据结构基础 层次遍历和中序遍历还原二叉树
- 根据二叉树的先序和中序遍历还原二叉树
- 由遍历序列还原二叉树结构
- 数据结构基础 后序遍历和中序遍历还原二叉树
- 根据一个树的中序遍历和前序遍历数据,还原一个二叉树的思考
- 根据遍历进行二叉树的还原
- 已知二叉树的先序(前序)遍历及中序遍历,还原该二叉树并输出其后续遍历
- 根据二叉树的中序遍序列和后续遍历序列还原一颗二叉树
- LeetCode之通过二叉树的中序遍历和后序遍历还原二叉树
- 如何根据前序、中序、后序遍历还原二叉树
- 利用前序遍历和中序遍历还原二叉树以及涉及的分治法思想
- 数据结构基础 后序遍历和中序遍历还原二叉树
- 每天一道LeetCode-----根据先序遍历和中序遍历还原二叉树
- L2-006. 树的遍历(利用后序中序还原二叉树)
- 二叉树三种遍历及还原
- 还原二叉树:层序遍历+中序遍历
- 用一棵二叉树的前序遍历结果和中序遍历结果还原这棵二叉树――6
- L2-006. 树的遍历(利用后序中序还原二叉树)
- 利用中序和后序遍历还原二叉树
- 二叉树的层次,中序非递归遍历,以递归前序的方式构造二叉树,将二叉树中的e更新为d,输出从根结点出发 到指定结点,依次经过的祖先(即路径),由前序和中序还原二叉树