码迷,mamicode.com
首页 > 其他好文 > 详细

PAT:1020. Tree Traversals (25) AC

时间:2015-03-07 06:10:30      阅读:135      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!