找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 905|回复: 0
收起左侧

二叉树的遍历

[复制链接]
ID:359038 发表于 2018-6-26 09:54 | 显示全部楼层 |阅读模式
#include<iostream>  
#include<malloc.h>  
#include<queue>  
#include<list>  
using namespace std;
struct node  
{  
    char c;  
    node *lchild,*rchild;  
};  
char pre[100],mid[100];
void build(node* &t,int start1,int end1,int start2,int end2)  
{  
    int i=start2;  
    while(pre[start1]!=mid[i])  
        i=i+1;  
    t=(node*)malloc(sizeof(node));  
    t->c=pre[start1];  
    if(i==start2)  
        t->lchild=NULL;  
    else build(t->lchild,start1+1,start1+i-start2,start2,i-1);  
    if(i==end2)  
        t->rchild=NULL;  
    else build(t->rchild,start1+i-start2+1,end1,i+1,end2);  
}  
list<node*> que;  
void visit(node *t)  
{  
    que.push_back(t);  
    while(!que.empty())  
    {  
        node *temp=que.front();  
        cout<<temp->c;  
        if(temp->lchild!=NULL)  
            que.push_back(temp->lchild);  
        if(temp->rchild!=NULL)  
            que.push_back(temp->rchild);  
        que.pop_front();  
    }  
    printf("");  
}  
void last(node *t)  
{  
    if(t==NULL)  
        return;  
    if(t->lchild!=NULL)  
        last(t->lchild);  
    if(t->rchild!=NULL)  
        last(t->rchild);  
    cout<<t->c;  
}  
int main()  
{  
    node *tree;  
    int length;  
    while(1==1)  
    {  
  printf("\n\n输出先序遍历:\n");
        cin>>pre;   
  printf("输出中序遍历:\n");
        cin>>mid;  
        length=strlen(pre);  
        build(tree,0,length-1,0,length-1);  
        if(!que.empty())  
            que.clear();  
  printf("层次遍历结果:\n");
        visit(tree);  
    }  
    return 0;  
}  
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|51黑电子论坛 |51黑电子论坛6群 QQ 管理员QQ:125739409;技术交流QQ群281945664

Powered by 单片机教程网

快速回复 返回顶部 返回列表