数据结构实验之二叉树五:层序遍历

来源:互联网 发布:ubuntu cpu 降频 编辑:程序博客网 时间:2024/04/29 13:00
#include <stdio.h>#include <stdlib.h>#include <queue>#include <iostream>using namespace std;char s[101];struct Node{    char data;    struct Node * lchild,* rchild;};struct Node * root;int cnt;//构造二叉树struct Node * Build_tree(){    struct Node * root;    if(s[cnt++] == ',') root = NULL;    else    {        root = (struct Node *)malloc(sizeof(struct Node));        root -> data = s[cnt - 1];        root -> lchild = Build_tree();        root -> rchild = Build_tree();    }    return root;}void cengcibianli(Node *root) //层次遍历{     queue<Node*>s;     if(root)        {        printf("%c", root->data);        s.push(root);        while(!s.empty())        {            root = s.front();            s.pop();            if(root->lchild)            {                printf("%c", root->lchild->data);                s.push(root->lchild);            }            if(root->rchild)            {                printf("%c", root->rchild->data);                s.push(root->rchild);            }        }     }}int main(){    int n;    cin>>n;    while(n--)    {        scanf("%s",s);        cnt = 0;        root = Build_tree(); //建树        cengcibianli(root);        cout<<endl;    }    return 0;}

0 0