#include <iostream>
using namespace std;
struct Node{//二叉树节点
int value;
Node *left;
Node *right;
};
struct queue{//辅助队列
int head;
int tail;
int len;//队列长度,遍历时用
Node ** list;//队列内容
void push(Node *n){
list[++tail] = n;
++len;
}
Node * pop(){
if(head <= tail) //判断
return list[head++];
else return 0;
}
queue(){//未写copy和赋值,丧失了原则。
len = head = 0;
tail = -1;
list = new Node*[100];
}
~queue(){delete[] list;}
};
//广度优先遍历
static queue breadth_first(Node * tree){
queue q;//初始化队列
q.push(tree);//先把根节点放入,后面没有可以放入的地方了。
q.pop();//然后取出。之后才是战场。如果不取出的话会重复的哦
while(tree){
if(tree->left){//左子树放入
q.push(tree->left);
}
if(tree->right){//右子树放入
q.push(tree->right);
}
tree = q.pop();//不停的从队列按照放入顺序取出,这样保证每一层数据都是挨着的。
}
return q;
}
//根据数组创建一只二叉树
static Node *createTree(int arr[], int start, int len){
if(start >= len) return 0;//递归中断-判断
//创建节点
Node *root = new Node;
root->value = arr[start];
root->left = createTree(arr, start*2+1, len);//果断递归
root->right = createTree(arr, start*2+2, len);//果断递归
return root;
}
int main(){
int arr[10] = {1,2,3,4,5,6,7,8,9,10};//数组一只
Node * tree = createTree(arr, 0, 10);//二叉树一只
queue res = breadth_first(tree);//广度优先
for(int i = 0; i < res.len; i++){//打印结果。
cout<<res.list[i]->value<<" ";
}
cout<<endl;
}
二叉树广度优先遍历
最新推荐文章于 2023-12-15 22:54:31 发布