二叉树层次遍历
二叉树按照层次遍历其实就相当于广度优先搜索,都可以通过队列这种数据结构很清楚的实现:
#include<stdio.h>
#include<stdlib.h>
#include<queue>
#include<iostream>
using namespace std;
typedef struct node{
char key;
struct node * left;
struct node * right;
}Node, *Tree;
queue<Tree> que;
void Create(Tree &t){ //先序建立二叉树,#表示当前节点的子树为空
char ch;
cin>>ch;
if(ch == '#')
t = NULL;
else{
t = (Tree)malloc(sizeof(Node));
t->key = ch;
Create(t->left);
Create(t->right);
}
}
void LevelTravel(Tree t){
if(t){
que.push(t); //根节点入队
}
while(!que.empty()){
Tree temp = que.front(); //每次取出队首元素
cout<<temp->key<<" ";
que.pop();
if(temp->left) //左右子树如果不为空,那么进队
que.push(temp->left);
if(temp->right)
que.push(temp->right);
}
}
int main(){
Tree t;
Create(t);
LevelTravel(t);
return 0;
}