二叉树的构造
来源:互联网 发布:python中sleep函数 编辑:程序博客网 时间:2024/04/26 05:41
我们假设二叉树中每个节点的值都不相同,那么二叉树具有唯一的先序序列、中序序列、后序序列(注意不同的二叉树可能有相同的先序、中序、后序序列)。引入如下两个定理(数学归纳法很容易可以证明,这里不给出证明):
1.任何n(n≥0)个不同节点的二叉树,都可由它的中序序列和先序序列唯一确定。
1.任何n(n≥0)个不同节点的二叉树,都可由它的中序序列和后序序列唯一确定。
给出二叉树的两个序列,返回出二叉树的根结点,代码如下:
/*Author:IbsenDate:2015.12.15*/#include <iostream>using namespace std;const int M=1000;typedef struct node{char data;struct node *lc,*rc;}BTree;BTree* Creat_BTree_pre_in(char *pre,char *in,int n){BTree *h;char *p;if(n<=0) return NULL;h=new BTree();h->data=*pre;for(p=in;p<in+n;p++)if(*p==*pre) break;int pos=p-in;h->lc=Creat_BTree_pre_in(pre+1,in,pos);h->rc=Creat_BTree_pre_in(pre+1+pos,p+1,n-1-pos);return h;}BTree* Creat_BTree_in_post(char *in,char *post,int n){BTree *h;char *p;if(n<=0) return NULL;h=new BTree();h->data=*(post+n-1);for(p=in;p<in+n;p++)if(*p==h->data) break;int pos=p-in;h->lc=Creat_BTree_in_post(in,post,pos);h->rc=Creat_BTree_in_post(p+1,post+pos,n-1-pos);return h;}void Display_BTree(BTree *h){if(h!=NULL){cout<<h->data;if(h->lc!=NULL||h->rc!=NULL){cout<<"(";Display_BTree(h->lc);if(h->rc!=NULL) cout<<",";Display_BTree(h->rc);cout<<")";}}}char pre[M],in[M],post[M]; //先序,中序,后序序列int main(){int n; //节点个数BTree *h;while(cin>>n){cin>>pre>>in>>post;h=Creat_BTree_pre_in(pre,in,n);Display_BTree(h);cout<<endl;h=Creat_BTree_in_post(in,post,n);Display_BTree(h);cout<<endl;}return 0;}
0 0
- 二叉树的构造
- 二叉树的构造
- 二叉树的构造
- 二叉树的构造
- 二叉树的构造
- 二叉树的构造
- 二叉树的构造
- 二叉树的构造
- 二叉树的构造 遍历
- 二叉树的构造方法
- 平衡二叉树的构造
- AVL树(平衡二叉树)的构造
- 二叉树 --- 树的构造和遍历
- 二叉树的java构造算法
- 线索二叉树的构造算法
- C++二叉树的构造和插入
- 完全二叉树的构造与遍历
- 排序二叉树的构造与遍历
- 《Android群英传》读书笔记(3)第四章:ListView常用拓展
- POJ-1157 LITTLE SHOP OF FLOWERS(动态规划)
- 【回溯】【leetcode题解】【M】【57】Combination Sum
- ArcEngine(ArcObjects) java开发环境配置
- mySQL中删除一个表中的某字段的unique key的语法
- 二叉树的构造
- Nazo游戏(11-20关)
- 我来了
- scala学习笔记(二)
- 手把手教你cuda5.5与VS2010的编译环境搭建
- HDOJ--2015
- 用一句话理解Docker
- 矛盾人生
- Android调启应用程序方法总结