题目来自剑指Offer
题目:层次遍历二叉树
代码:
#include <iostream>
#include <assert.h>
using namespace std;
const int SIZE = 100;
struct BinaryTreeNode
{
char m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
void LevelOrder(BinaryTreeNode* pRoot)
{
if (!pRoot)
{
cout<<"空树!"<<endl;
return;
}
BinaryTreeNode* Queue[SIZE];
int nRear = 0;
int nFront = 0;
BinaryTreeNode* pNode = NULL;
Queue[nRear++] = pRoot;
while (nRear != nFront)
{
pNode = Queue[(nFront++)%SIZE];
cout<<pNode->m_nValue<<" ";
if (pNode->m_pLeft)
{
Queue[(nRear++)%SIZE] = pNode->m_pLeft;
}
if (pNode->m_pRight)
{
Queue[(nRear++)%SIZE] = pNode->m_pRight;
}
}
}
void Create(BinaryTreeNode*& pRoot)
{
char newData;
cin >> newData;
if ('#' == newData)
{
pRoot = NULL;
}
else
{
pRoot = new BinaryTreeNode;
pRoot->m_nValue = newData;
Create(pRoot->m_pLeft);
Create(pRoot->m_pRight);
}
}
int main()
{
BinaryTreeNode* Root = NULL;
Create(Root);
LevelOrder(Root);
system("pause");
return 1;
}
注意:
树的输入类似树的子结构,这里不再详述。