利用广义表非递归构造二叉树

来源:互联网 发布: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)

原创粉丝点击