第16 题:
题目(微软):
输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印。
例如输入
8
/ \
6 10
/ \ / \
5 7 9 11
输出8 6 10 5 7 9 11。
使用队列数据结构,并且在每一层的末尾插入一个节点表示换行。
代码:
#include <queue>
#include <iostream>
using namespace std;
struct BSTreeNode
{
void printTree()
{
std::queue<BSTreeNode *> anQueue;
anQueue.push(this);
BSTreeNode enterNode;
enterNode.m_fEnterFlag = true;
enterNode.m_pLeft = NULL;
enterNode.m_pRight = NULL;
anQueue.push(&enterNode);
while(anQueue.size() > 0)
{
BSTreeNode *node = anQueue.front();
anQueue.pop();
if (!node->m_fEnterFlag)
{
cout << node->m_nValue << " ";
if (node->m_pLeft)
anQueue.push(node->m_pLeft);
if (node->m_pRight)
anQueue.push(node->m_pRight);
}
else
{
cout << endl;
if (anQueue.size() > 0)
{
anQueue.push(node);
}
}
}
}
bool m_fEnterFlag;
int m_nValue;
BSTreeNode *m_pLeft;
BSTreeNode *m_pRight;
};
int main(void)
{
BSTreeNode node[12];
node[8].m_fEnterFlag = false;
node[8].m_nValue = 8;
node[8].m_pLeft = &node[6];
node[8].m_pRight = &node[10];
node[6].m_fEnterFlag = false;
node[6].m_nValue = 6;
node[6].m_pLeft = &node[5];
node[6].m_pRight = &node[7];
node[10].m_fEnterFlag = false;
node[10].m_nValue = 10;
node[10].m_pLeft = &node[9];
node[10].m_pRight = &node[11];
node[5].m_fEnterFlag = false;
node[5].m_nValue = 5;
node[5].m_pLeft = NULL;
node[5].m_pRight = NULL;
node[7].m_fEnterFlag = false;
node[7].m_nValue = 7;
node[7].m_pLeft = NULL;
node[7].m_pRight = NULL;
node[9].m_fEnterFlag = false;
node[9].m_nValue = 9;
node[9].m_pLeft = NULL;
node[9].m_pRight = NULL;
node[11].m_fEnterFlag = false;
node[11].m_nValue = 11;
node[11].m_pLeft = NULL;
node[11].m_pRight = NULL;
node[8].printTree();
system("pause");
return 0;
}