创建一个二叉树,广度优先遍历。
照着书上写的,但结果不对(正确结果是输入什么输出什么)
/*广度优先算法*/
#include<iostream>
#include<queue>
using namespace std;
void visit(char x)
{
cout<<x<<" ";
}
template<class T>
class BinaryTreeNode{
private:
T data;
BinaryTreeNode<T>* leftchild;
BinaryTreeNode<T>* rightchild;
public:
BinaryTreeNode()
{
leftchild=NULL;
rightchild=NULL;
}
BinaryTreeNode(T _data)
{
data=_data;
}
BinaryTreeNode(T _data,BinaryTreeNode<T>* left=NULL,BinaryTreeNode<T>* right=NULL)
{
data=_data;
leftchild=left;
rightchild=right;
}
BinaryTreeNode<T>* getLeftChild()const
{
return leftchild;
}
BinaryTreeNode<T>* getRightChild()const
{
return leftchild;
}
void setLeftChild(BinaryTreeNode<T>* l)
{
leftchild=l;
}
void setRightChild(BinaryTreeNode<T>* r)
{
rightchild=r;
}
T getvalue()const
{
return data;
}
void setvalue(const T& x)
{
data=x;
}
bool isLeaf()const
{
if(leftchild==NULL&&rightchild==NULL)
return true;
else
return false;
}
};
template<class T>
class BinaryTree{
private:
BinaryTreeNode<T>* root;
public:
BinaryTree(BinaryTreeNode<T>* _root)
{
root=_root;
}
void deleteBinaryTree(BinaryTreeNode<T>* root)
{
if (root->getLeftChild()!= NULL)
deleteBinaryTree(root->getLeftChild());
if (root->getRightChild()!= NULL)
deleteBinaryTree(root->getRightChild());
delete root;
root = NULL;
}
bool isEmpty()const
{
if(root==NULL)
return true;
else
return false;
}
BinaryTreeNode<T>* getRoot()const
{
return root;
}
void levelOrder(BinaryTreeNode<T>* root)//广度优先遍历
{
using std::queue;
queue<BinaryTreeNode<T> *> aQueue;
BinaryTreeNode<T>* pointer=root;
if(pointer)
aQueue.push(pointer);
while(!aQueue.empty())
{
pointer=aQueue.front();
aQueue.pop();
visit(pointer->getvalue());
if(pointer->getLeftChild()!=NULL)
aQueue.push(pointer->getLeftChild());
if(pointer->getRightChild()!=NULL)
aQueue.push(pointer->getRightChild());
}
}
};
//按照前序顺序建立二叉树
BinaryTreeNode<char>* creatBinaryTree()
{
BinaryTreeNode<char> * temp=new BinaryTreeNode<char>;
char c;
cout<<"按照前序顺序输入要建立的二叉树"<<endl;
cin>>c;
if(c=='#')//当遇到#时,令树的根节点为NULL,从而结束该分支的递归
temp=NULL;
else
{
temp->setvalue(c);
temp->setLeftChild(creatBinaryTree());
temp->setRightChild(creatBinaryTree());
}
return temp;
}
int main()
{
BinaryTreeNode<char> * root=creatBinaryTree();
BinaryTree<char> B(root);
cout<<"广度优先遍历的输出顺序为:"<<endl;
B.levelOrder(root);
}