找回密碼
 立即注冊

QQ登錄

只需一步,快速開始

搜索
查看: 1171|回復(fù): 0
打印 上一主題 下一主題
收起左側(cè)

二叉樹的遍歷

[復(fù)制鏈接]
跳轉(zhuǎn)到指定樓層
樓主
ID:359038 發(fā)表于 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("層次遍歷結(jié)果:\n");
        visit(tree);  
    }  
    return 0;  
}  
分享到:  QQ好友和群QQ好友和群 QQ空間QQ空間 騰訊微博騰訊微博 騰訊朋友騰訊朋友
收藏收藏 分享淘帖 頂 踩
回復(fù)

使用道具 舉報

您需要登錄后才可以回帖 登錄 | 立即注冊

本版積分規(guī)則

手機版|小黑屋|51黑電子論壇 |51黑電子論壇6群 QQ 管理員QQ:125739409;技術(shù)交流QQ群281945664

Powered by 單片機教程網(wǎng)

快速回復(fù) 返回頂部 返回列表