void BFS(BinaryTreeNode* pRoot)
{
if(pRoot==nullptr)
{
cout<<"empty binary tree!"<<endl;
return;
}
queue<BinaryTreeNode*>pNode;
pNode.push(pRoot);
while(!pNode.empty())
{
BinaryTreeNode* pFront=pNode.front();
pNode.pop();
cout<<pFront->m_Value<<' ';
if(pFront->m_pLeft!=nullptr)
pNode.push(pFront->m_pLeft);
if(pFront->m_pRight!=nullptr)
pNode.push(pFront->m_pRight);
}
cout<<endl;
}

函数

 #include"BinaryTree.h"

 void Test()
{
BFS(nullptr);
BinaryTreeNode* pNode1=CreateBinaryTreeNode();
BFS(pNode1);
BinaryTreeNode* pNode2=CreateBinaryTreeNode();
ConnectTreeNodes(pNode1,pNode2,nullptr);
BFS(pNode1);
ConnectTreeNodes(pNode1,nullptr,pNode2);
BFS(pNode1);
BinaryTreeNode* pNode3=CreateBinaryTreeNode();
ConnectTreeNodes(pNode1,pNode2,pNode3);
BFS(pNode1);
} int main()
{
Test();
return ;
}

测试代码

04-14 06:05