数据结构实验之二叉树五:层序遍历(STL和模拟队列两种方法)
生活随笔
收集整理的這篇文章主要介紹了
数据结构实验之二叉树五:层序遍历(STL和模拟队列两种方法)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Description
已知一個按先序輸入的字符序列,如abd,eg,cf,(其中,表示空結(jié)點)。請建立二叉樹并求二叉樹的層次遍歷序列。
Input
輸入數(shù)據(jù)有多行,第一行是一個整數(shù)t (t<1000),代表有t行測試數(shù)據(jù)。每行是一個長度小于50個字符的字符串。
Output
輸出二叉樹的層次遍歷序列。
Sample
Input
Output
abcdefg xnuliHint
#include<bits/stdc++.h>using namespace std;typedef struct node {char data;struct node *l, *r; } Tree;char pre[55]; int cnt;Tree *creat() {Tree *root;if(pre[cnt] == ','){cnt++;root = NULL;}else{root = new Tree;root->data = pre[cnt++];root->l = creat();root->r = creat();}return root; } void cengxu(Tree *root)//模擬隊列實現(xiàn)層序遍歷 {Tree *que[10000];int i, j;i = 0, j = 0;que[i++] = root;while(i > j){if(que[j]){printf("%c", que[j]->data);que[i++] = que[j]->l;que[i++] = que[j]->r;}j++;} } /*void cengxu(Tree *root)//用STL中的queue隊列實現(xiàn) {Tree* temp;queue<Tree *>q;q.push(root);//首先根節(jié)點入隊//將根節(jié)點壓入隊列,每次再從隊列中取出隊首//每次先輸出取出的節(jié)點的值,再將該節(jié)點的左右節(jié)點壓入隊列(有的話)while(!q.empty()){temp = q.front();q.pop();if(temp){printf("%c", temp->data);if(temp->l)q.push(temp->l);if(temp->r)q.push(temp->r);}} }*/ int main() {int t;scanf("%d", &t);while(t--){cnt = 0;scanf("%s", pre);Tree *root = creat();cengxu(root);printf("\n");}return 0; }總結(jié)
以上是生活随笔為你收集整理的数据结构实验之二叉树五:层序遍历(STL和模拟队列两种方法)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据结构实验之二叉树七:叶子问题
- 下一篇: 二叉树(前序遍历序列、中序遍历序列、后序