/*不管是广度优先遍历一个有向图还是一棵树,都要用到队列,第一步把起始结点(对树而言是根结点)放入到队列中,
接下来每一次从队列头部提取出一个结点,遍历这个结点之后把从它能到达的结点(对树而言是子结点)都依次放入到队列,
我们重复这个遍历过程,直到队列中的结点全部被遍历为止
*/
/*从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序*/
#include <iostream>
#include <queue>
using namespace std;
//定义二叉树结点
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode *m_pLeft;
BinaryTreeNode *m_pRight;
};
//创建二叉树结点
BinaryTreeNode *CreateTreeNode(int ival)
{
BinaryTreeNode *OneNode = new BinaryTreeNode();
OneNode -> m_nValue = ival;
OneNode -> m_pLeft = NULL;
OneNode -> m_pRight = NULL;
}
//连接二叉树结点
void ConnectBinaryTreeNodes(BinaryTreeNode *pRoot, BinaryTreeNode *pLeft, BinaryTreeNode *pRight)
{
pRoot -> m_pLeft = pLeft;
pRoot -> m_pRight = pRight;
}
//从上到下打印二叉树
void PrintFromTopToBottom(BinaryTreeNode *pRootNode)
{
//判断是否为空树
if(!pRootNode)
return;
//定义一个队列存放需要打印的二叉树结点指针
queue<BinaryTreeNode *> pQueue;
//根结点入队
pQueue.push(pRootNode);
while(pQueue.size())//size()返回队列中的元素个数
{
BinaryTreeNode *pNode = pQueue.front();//front()返回队首元素,适用于队列
pQueue.pop();//删除队首元素但不返回其值
cout << pNode -> m_nValue << " ";//打印结点值
//左结点非零,入队
if(pNode -> m_pLeft)
pQueue.push(pNode -> m_pLeft);
//右结点非零,入队
if(pNode -> m_pRight)
pQueue.push(pNode -> m_pRight);
}
}
//======测试代码======
//======测试用例======
/*
8
/ \
6 10
/ \ / \
5 7 9 11
*/
void Test1()
{
BinaryTreeNode *pNode1 = CreateTreeNode(8);
BinaryTreeNode *pNode2 = CreateTreeNode(6);
BinaryTreeNode *pNode3 = CreateTreeNode(10);
BinaryTreeNode *pNode4 = CreateTreeNode(5);
BinaryTreeNode *pNode5 = CreateTreeNode(7);
BinaryTreeNode *pNode6 = CreateTreeNode(9);
BinaryTreeNode *pNode7 = CreateTreeNode(11);
ConnectBinaryTreeNodes(pNode1, pNode2, pNode3);
ConnectBinaryTreeNodes(pNode2, pNode4, pNode5);
ConnectBinaryTreeNodes(pNode3, pNode6, pNode7);
PrintFromTopToBottom(pNode1);
}
//输入为空
void Test2()
{
PrintFromTopToBottom(NULL);
}
int main()
{
Test1();
Test2();
return 0;
}
面试题23:从上往下打印二叉树
最新推荐文章于 2020-02-22 16:26:57 发布