SJTU OJ (1111)

本文介绍了一种使用前序和中序遍历构建二叉树的方法,并通过链式队列实现了树的层次遍历。具体展示了如何定义节点结构、构建二叉树以及利用链式队列进行遍历的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;

template <class elemType>
class linkQueue{
  private:
      struct node{
        elemType data;
        node *next;
        node(const elemType &x,node *p=NULL){data=x; next=p;}
        node():next(NULL){}
        ~node(){}
      };
      node *Front,*rear;
  public:
    linkQueue(){Front=rear=NULL;}
    ~linkQueue();
    void enQueue(const elemType &x);
    elemType deQueue();
    bool isEmpty(){return (Front==NULL);}
    elemType getHead(){return Front->data;}
};

template <class elemType>
linkQueue<elemType>::~linkQueue(){
  node *q=Front,*p;
  while(q!=NULL){
    p=q->next;
    delete q;
    q=p;
  }
}

template <class elemType>
void linkQueue<elemType>::enQueue(const elemType &x){
  node *tmp;
  if (Front==NULL) {
    tmp=new node(x);
    rear=Front=tmp;
  }
  else{
    tmp=new node(x);
    rear->next=tmp;
    rear=tmp;
  }
}

template <class elemType>
elemType linkQueue<elemType>::deQueue(){
  node *tmp;
  elemType value=Front->data;
  tmp=Front;
  Front=Front->next;
  if (Front==NULL) rear=NULL;
  delete tmp;
  return value;
}


struct Node{
  char data;
  Node *left,*right;
  Node(char x,Node *lt=NULL,Node *rt=NULL):data(x),left(lt),right(rt){}
  Node():left(NULL),right(NULL){}
  ~Node(){}
};

Node *buildTree(char pre[],int s1,int e1,char mid[],int s2,int e2){
  Node *p;
  int pos;
  if (s1>e1) return NULL;
  p=new Node(pre[s1]);
  for (int i=s2;i<=e2;i++)
    if (mid[i]==pre[s1]){
       pos=i;
       break;
    }
  p->left=buildTree(pre,s1+1,s1+pos-s2,mid,s2,pos-1);
  p->right=buildTree(pre,s1+pos-s2+1,e1,mid,pos+1,e2);
  return p;
}


void result(Node *root,int l){
  linkQueue<Node *> que;
  Node *p;
  int ct=0;
  que.enQueue(root);
  while ((!que.isEmpty())&& ct<l){
    p=que.deQueue();
    if (p) {cout<<p->data<<' '; ct++; que.enQueue(p->left); que.enQueue(p->right);}
    else {cout<<"NULL"<<' '; que.enQueue(NULL); que.enQueue(NULL);}
  }
}

int main()
{
    char pre[27],mid[27];
    Node *root;
    int l1,l2;
    cin>>pre;
    cin>>mid;

    l1=strlen(pre);
    root=buildTree(pre,0,l1-1,mid,0,l1-1);
    result(root,l1);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值