利用广义表非递归构造二叉树
来源:互联网 发布:2015年流行的网络歌曲 编辑:程序博客网 时间:2024/04/30 09:49
#include<iostream>
using namespace std;
const int nax=100;
typedef struct tr
{
int data,left,right;
int label;
}btree;
btree tree[100];
bool ck[100];
int recreat(int *mid,int *post,int len)//len结点个数
{
int i,j,root=0,troot;//troot是暂时根节点
for(i=0;i<len;i++)
{
tree[i].data=mid[i];
tree[i].left=tree[i].right=-1;
tree[i].label=i;
}
while(post[len-1]!=tree[root].data)//寻找根节点在中序遍历数组中的位置
root++;
/*从后序节点的倒数第二个开始扫描,依次与中序遍历的节点比较,找到其中序数组中的位置时,
用j记录下来,然后比较他的label值与根节点的label值,看看是左孙子,还是右孙子*/
for(i=len-2;i>=0;i--)
{
troot=root;
j=0;
while(post[i]!=tree[j].data)j++;
while(troot!=-1)
{
if(tree[j].label<tree[troot].label)//插在左侧
{
if(tree[troot].left==-1)
{
tree[troot].left=j;
troot=-1;
}
else
troot=tree[troot].left;
}
else
if(tree[j].label>tree[troot].label)
{
if(tree[troot].right==-1)
{
tree[troot].right=j;
troot=-1;
}
else
troot=tree[troot].right;
}
}
}
return root;
}
void displaya(int root)//按照中序左根右的顺序输出,递归的详细版
{
if (tree[root].left!=-1 && tree[root].right!=-1)
{
displaya(tree[root].left);
printf("%d ",tree[root].data);
displaya(tree[root].right);
}
else if (tree[root].left==-1 && tree[root].right!=-1)
{
printf("%d ",tree[root].data);
displaya(tree[root].right);
}
else if (tree[root].right==-1 && tree[root].left!=-1)
{
displaya(tree[root].left);
printf("%d ",tree[root].data);
}
else printf("%d ",tree[root].data);
}
void displayb(int root)//先序根左右
{
if(root!=-1)
{
printf("%d ",tree[root].data);
displayb(tree[root].left);
displayb(tree[root].right);
}
}
int main()
{
int i,n,mid[nax],post[nax];
memset(ck,0,sizeof(ck));
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&mid[i]);
for(i=0;i<n;i++)
scanf("%d",&post[i]);
//display(recreat(mid,post,n));
displayb(recreat(mid,post,n));
return false;
}
文章出处:DIY部落(http://www.diybl.com/course/3_program/c++/cppjs/20091012/178565.html)
- 利用广义表非递归构造二叉树
- 旧话重提续,根据后序和中序遍历利用广义表非递归构造二叉树
- 非递归构造二叉查找树
- 二叉树的查找、二叉树高度、二叉树获得双亲结点、构造二叉树、二叉树的广义表表示法、二叉树的插入删除、二叉树的非递归实现
- 二叉树的构造,递归遍历,非递归遍历
- 递归创建二叉树,前序,中序,后序遍历二叉树,广义表创建二叉树,非递归前序,中序,后序遍历二叉树
- 二叉树非递归
- 非递归二叉树
- 二叉树非递归
- 非递归二叉树
- 递归、非递归~二叉树
- 二叉树 递归 非递归
- 数据结构--非递归遍历二叉树(利用辅助栈)
- 利用java实现二叉树以及非递归遍历算法
- 利用层次遍历非递归求二叉树高度
- 用二叉链表存储结构构造一棵二叉树,然后用栈结构进行非递归遍历
- 关于二叉树以及利用二叉树将递归转化为非递归
- 广义表建立二叉树
- 将str1缓冲区的50个字节数据按照相反的方向依次传送到存储区str2中
- WIN网络编程-NetTime
- 用Excel+VBA+SQL Server进行数据处理
- WIN网络编程-UDPClient
- ASP.NET - 保证登录控件的安全
- 利用广义表非递归构造二叉树
- 二叉树
- WIN网络编程-UDPServer
- 收录一些欧美优秀css网站
- WIN网络编程-TCPClient
- WIN网络编程-TCPServer
- 小汇编习题"HELLO?"
- java
- VBA使用备忘录