二叉树的建立和遍历

来源:互联网 发布:记分牌算法 编辑:程序博客网 时间:2024/06/03 19:36

首先,有一颗二叉树,形如:

有了要建立的二叉树,就好办了。只要在输入数据时输入DBA##C##EF##G##即可。
先用一个结构体来定义二叉树

typedef struct node{    struct node *lc; //左孩子    struct node *rc; //右孩子    char data;}NODE;  

之后,在写一个函数,递归建立二叉树,在主函数中调用即可。

NODE *buildTrea(){    char a;    cin>>a;    if(a=='#') return NULL;    NODE *t = new node;    t->date = a;    t->lc = buildTree();    t->rc = buildTree();    return t;}

二叉树建好之后,就可以进行遍历了,遍历二叉树有,前序遍历,中序遍历,后序遍历。这三种遍历方式,代码都不长,是有规律的。

//前序遍历void preorder(NODE *t){    if(t!=NULL){        cout<<t-data;        preorder(t->lc);        preorder(t->rc);    }}
//中序遍历void inorder(NODE *t){    if(t!=NULL){        inorder(t->lc);        cout<<t->data;        inorder(t->rc);    }}
//后序遍历void postorder(NODE *t){    if(t!=NULL){        postorder(t->lc);        postorder(t->rc);        cout<<t->data;    }}

其实,观察以上三段代码,不难发现规律,就是输出语句放在,if语句中的,前中后的那个位置之中,就是那种方式进行遍历二叉树。
出以上三种方式遍历二叉树以外,还有镜像遍历,层次遍历。

镜像遍历和中序遍历,很像。层次遍历,就是互换左右孩子,

//镜像遍历void mirror(NODE *t){    if(t!=NULL){        mirror(t->rc);        cout<<t->data;        mirror(t->lc);    }}

层次遍历,顾名思义,就是一层一层的遍历。如图:
这里写图片描述

//层次遍历,这里使用队列(queue)//先进先出void level(NODE *t){    queue<NODE*>q;    NODE *root = t;    while(t==NULL) return;    q.push(t); //放入队列    while(!q.empty()){        root = q.front();  //获取最前的一个        cout<<root->data;        q.pop();    //弹出        if(root->lc!=NULL) q.push(root->lc);        if(root->rc!=NULL) q.push(root->rc);    }}

完整代码:

#include<iostream>#include<algorithm>#include<queue>using namespace std;typedef struct node{    char date;    struct node *lc;    struct node *rc;}NODE;NODE* buildTree(){    char a;    cin>>a;    if(a=='#')return NULL;    NODE *p = new node;    p->date = a;    p->lc = buildtree();    p->rc = buildtree();    return p; }//前序遍历 void preorder(NODE *t){    if(t!=NULL){        cout<<t->date;        preorder(t->lc);        preorder(t->rc);     } }//中序遍历void inorder(NODE *t){    if(t!=NULL){        inorder(t->lc);        cout<<t->date;        inorder(t->rc);    } } //后序遍历 void postorder(NODE *t){    if(t!=NULL){        postorder(t->lc);        postorder(t->rc);        cout<<t->date;     }}//镜像遍历 void mirror(NODE *t){    if(t!=NULL){        mirror(t->rc);        cout<<t->date;        mirror(t->lc);    }}//层次遍历 void level(NODE *t){    queue<NODE*>q;    NODE *root = t;    while(t==NULL) return;    q.push(t);    while(!q.empty()){        root = q.front();        cout<<root->date;        q.pop();        if(root->lc!=NULL) q.push(root->lc);        if(root->rc!=NULL) q.push(root->rc);;     }}int main(){    NODE *root = NULL;    root = buildtree();     preorder(root);    cout<<endl;    inorder(root);    cout<<endl;    postorder(root);    cout<<endl;    mirror(root);    cout<<endl;    level(root);}

PS:之前在做测试的时候,用过数字进行测试,421003005600700,但是,输出的结果总是2147483647,纳闷好久,现在我也搞不懂,自己真的是太菜了。换了DBA##C##EF##G##,这组数据,结果和自己想得一样。

原创粉丝点击