这里要求用队列实现,反而好做点,输出头节点的数据,然后他就该出队了
然后他的左右孩子进队列
看看深大灵魂画手的作品
#include <bits/stdc++.h>
using namespace std;
class BiTreeNode{
public:
char date;
BiTreeNode *leftchild;
BiTreeNode *rightchild;
};
class BiTree{
private:
BiTreeNode *Root; //根节点指针
int pos;
string strTree;
BiTreeNode *CreateBirtree();
public:
void CreateTree(string TreeArray);//利用先序遍历结果创建二叉树
void LevelOrder(){LevelOrder(Root);}
void LevelOrder(BiTreeNode *t);
};
//构造二叉树,利用先序遍历结果创建树
void BiTree::CreateTree(string TreeArray){
pos=0;
strTree.assign(TreeArray);
Root=CreateBirtree();
}
//递归建树,私有函数,类内实现
BiTreeNode* BiTree::CreateBirtree(){
BiTreeNode *T;
char ch;
ch=strTree[pos++];
int flag=0;
if(ch=='0') T=NULL;
else{
T=new BiTreeNode();
T->date=ch;// 生成根节点
T->leftchild=CreateBirtree();// 构造左子树
T->rightchild=CreateBirtree();//构造右子树
}
return T;
}
//定义层次遍历函数
void BiTree::LevelOrder(BiTreeNode* t) {
//用队列实现
queue<BiTreeNode*> tq;
BiTreeNode *p;
tq.push(t);
while(!tq.empty()) {
p=tq.front();//p代表头节点
cout<<p->date;//输出头节点数据
if(p->leftchild)//分别判断防止没孩子
tq.push(p->leftchild);//有孩子则按左右顺序进队列
if(p->rightchild)
tq.push(p->rightchild);
tq.pop();
}
}
int main()
{
//输入t,表示有t个字符串输入
int t;cin>>t;
for (int i = 0; i < t; ++i) {
string str; cin>>str;
BiTree *tree;
tree=new BiTree();
tree->CreateTree(str);
tree->LevelOrder();
cout<<endl;
}
}