首页 > 其他 > 详细

PAT:1020. Tree Traversals (25) AC

时间:2015-03-07 06:07:48      阅读:280      评论:0      收藏:0      [点我收藏+]
#include<stdio.h>
#include<stdlib.h>
#include<queue>
using namespace std;

int POST[32];      //存放后序遍历
int IN[32];        //存放中序遍历
int n;          //节点数
struct node
{
  int data;
  node* l;
  node* r;
};

node* creat(int postL,int postR,int inL,int inR)
 {
  if(postL>postR)    //表明后续已经遍历完了
    return NULL;
  node* root=(node*)calloc(1,sizeof(node));    //或者写成  node* root=new node;  而calloc会自动初始化root更方便
  root->data=POST[postR];
  root->l=NULL;
  root->r=NULL;
  int tmp=0;      //标记postR这个元素在中序遍历下的位置
  for(tmp=inL ; tmp<=inR ; ++tmp)
    if(IN[tmp]==root->data)
      break;
  int numleft=tmp-inL;  //【思维】后序遍历中,前numleft个数字都是后续根的左子树
  root->l=creat(postL, postL+numleft-1, inL, tmp-1);    //【caution】这里的下标千万注意!!!
  root->r=creat(postL+numleft , postR-1 , tmp+1 , inR);  //写这步的时候最好画图
  return root;    //返回根地址
}

void BFS(node* root)
{
  queue<node*> q;    //创建队列
  q.push(root);
  int num=0;      //记录输出个数,控制空格数量
  while(!q.empty())
  {
    ++num;
    node* tmp=q.front();
    q.pop();
    printf("%d",tmp->data);
    if(num<n)
      printf(" ");
    if(tmp->l!=NULL)
      q.push(tmp->l);
    if(tmp->r!=NULL)
      q.push(tmp->r);
  }
}

void DFS(node* root)
{
  if(root==NULL)
    return;
  printf("%d ",root->data);
  DFS(root->l);
  DFS(root->r);
}

int main()
{
  scanf("%d",&n);
  for(int i=0 ; i<n ; ++i)
    scanf("%d",&POST[i]);
  for(int i=0 ; i<n ; ++i)
    scanf("%d",&IN[i]);
  node* root=creat(0,n-1,0,n-1);

  //DFS(root);    //先序遍历,测试建树情况

  BFS(root);

  return 0;
}

PAT:1020. Tree Traversals (25) AC

原文:http://www.cnblogs.com/Evence/p/4319614.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!