廣度優先遍歷二叉樹(從上到下遍歷二叉樹)
阿新 • • 發佈:2019-01-07
問題描述:從上到下打印出二叉樹的每個結點,同一層的結點按照從左到右的順序列印。例如下圖中的二叉樹 ,則依次打印出8,6,10,5,7,9,11
思路分析:按層列印的順序決定了應該先列印根節點,所以我們從樹的根節點開始分析,為了接下來能夠列印值為8的結點的兩個子結點,我們應該在遍歷到該結點時把值為6和10的兩個結點儲存到一個容器裡,現在容器內就有兩個結點了。按照從左到右的列印,我們先取出值為6的結點,打印出值6之後把它的值分別為5和7的兩個結點放入資料容器。此時資料容器中有3個結點,值分別為10,5,7。接下來我們從資料容器中取出值為10的結點。注意到值為10的結點比值為5,7的結點先放入容器中,此時又比這兩個結點先取出,這就是先入先出。因此,不難看出這個資料容器應該就是一個佇列。由於值為5,7,9,11的結點都沒有子結點,因此只要依次列印即可。
完整程式碼:
#include<iostream>
#include<deque>
using namespace std;
typedef struct BinaryTreeNode{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
//建立一顆二叉樹
void CreateBinaryTreeNode(BinaryTreeNode* &pCurrent,int value)
{
if(pCurrent==NULL)
{
BinaryTreeNode* pNode=new BinaryTreeNode();
if(pNode==NULL)
{
throw exception("Allocate Failure");
}
pNode->m_pLeft=NULL;
pNode->m_pRight=NULL;
pNode->m_nValue=value;
pCurrent=pNode;
}
else{
if(pCurrent->m_nValue>value)
{
CreateBinaryTreeNode(pCurrent->m_pLeft,value);
}
else if(pCurrent->m_nValue<value)
{
CreateBinaryTreeNode(pCurrent->m_pRight,value);
}
else{
cout<<"重複加入結點"<<endl;
}
}
}
//核心程式碼:從上到下列印二叉樹
void PrintFromTopToBottom(BinaryTreeNode* pTreeNode)
{
if(pTreeNode==NULL)
{
return;
}
deque<BinaryTreeNode*> dequeTreeNode;
dequeTreeNode.push_back(pTreeNode);//頭結點放入佇列中
while(dequeTreeNode.size())//迴圈取出結點
{
BinaryTreeNode* pNode=dequeTreeNode.front();//取出佇列中的第一個元素
dequeTreeNode.pop_front();//第一個元素出佇列
cout<<pNode->m_nValue<<"\t";
if(pNode->m_pLeft)
{
dequeTreeNode.push_back(pNode->m_pLeft);
}
if(pNode->m_pRight)
{
dequeTreeNode.push_back(pNode->m_pRight);
}
}
}
//前序遍歷
void PreOrderTraverseTree(BinaryTreeNode* pRoot)
{
if(pRoot==NULL)
{
return;
}
cout<<pRoot->m_nValue<<"\t";
PreOrderTraverseTree(pRoot->m_pLeft);
PreOrderTraverseTree(pRoot->m_pRight);
}
//中序遍歷
void InorderTraverseTree(BinaryTreeNode* pRoot)
{
if(pRoot==NULL)
{
return;
}
InorderTraverseTree(pRoot->m_pLeft);
cout<<pRoot->m_nValue<<"\t";
InorderTraverseTree(pRoot->m_pRight);
}
//後序遍歷
void PastorderTraverseTree(BinaryTreeNode* pRoot)
{
if(pRoot==NULL)
{
return;
}
PastorderTraverseTree(pRoot->m_pLeft);
PastorderTraverseTree(pRoot->m_pRight);
cout<<pRoot->m_nValue<<"\t";
}
int main()
{
BinaryTreeNode* pRoot=NULL;
CreateBinaryTreeNode(pRoot,8);
CreateBinaryTreeNode(pRoot,6);
CreateBinaryTreeNode(pRoot,5);
CreateBinaryTreeNode(pRoot,7);
CreateBinaryTreeNode(pRoot,10);
CreateBinaryTreeNode(pRoot,9);
CreateBinaryTreeNode(pRoot,11);
cout<<"前序遍歷:"<<endl;
PreOrderTraverseTree(pRoot);
cout<<endl;
cout<<"中序遍歷:"<<endl;
InorderTraverseTree(pRoot);
cout<<endl;
cout<<"後序遍歷:"<<endl;
PastorderTraverseTree(pRoot);
cout<<endl;
cout<<"從上往下列印二叉樹"<<endl;
PrintFromTopToBottom(pRoot);
cout<<endl;
system("pause");
return 0;
}
結果如下圖: