背景:二叉树的遍历,在计算机专业课程《数据结构》中应该都学习过。但很可惜,我是半道出家,没有系统化学习过,呵呵~~
最近看到一个题目,要求按层次遍历一颗二叉数,想检测一下自身的基本功底,所以就有了本文的诞生。
基本思想:首先将二叉树根节点入队列,然后开始逐个出队列操作,每出一个节点,就将该节点的左右孩子依次入队列,以此循环,直到所有的节点进行了“入队列--出队列”的操作为止。
例程:
#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "windows.h"
#include <queue>
using namespace std;
struct T_Node
{
int iData;
T_Node *pLeftChild;
T_Node *pRightChild;
};//定义二叉树的node数据结构
std::queue <T_Node*> q;//定义一个队列
T_Node *pTreeRoot = NULL;//二叉树根
//createTree函数,用于创建一颗测试二叉树
int createTree()
{
T_Node *pNode = new T_Node();
pNode->iData = 1;
pTreeRoot = pNode;
pNode = new T_Node();
pNode->iData = 2;
pTreeRoot->pLeftChild = pNode;
pNode = new T_Node();
pNode->iData = 4;
pTreeRoot->pLeftChild->pLeftChild = pNode;
pNode = new T_Node();
pNode->iData = 8;
pTreeRoot->pLeftChild->pLeftChild->pLeftChild = pNode;
pNode = new T_Node();
pNode->iData = 9;
pTreeRoot->pLeftChild->pLeftChild->pRightChild = pNode;
pNode = new T_Node();
pNode->iData = 5;
pTreeRoot->pLeftChild->pRightChild = pNode;
pNode = new T_Node();
pNode->iData = 3;
pTreeRoot->pRightChild = pNode;
pNode = new T_Node();
pNode->iData = 6;
pTreeRoot->pRightChild->pLeftChild = pNode;
pNode = new T_Node();
pNode->iData = 7;
pTreeRoot->pRightChild->pRightChild = pNode;
return 0;
}
void visitTree(T_Node *pRoot)
{
static int iRootFlag = 1;//定义一个标志,用于标志根节点
if (NULL != pRoot)
{
if (1== iRootFlag)//如果是根节点,那么将根节点入队列,并将标志设置为0,注意:这里的使用有些缺陷,但作为测试代码,讲究是速度哈,呵呵,原因不多说哈,自己想!
{
q.push(pRoot);
iRootFlag = 0;
}
if (NULL != pRoot->pLeftChild)//左孩子入队列
{
q.push(pRoot->pLeftChild);
}
if (NULL != pRoot->pRightChild)//右孩子入队列
{
q.push(pRoot->pRightChild);
}
printf("%d",q.front()->iData);//打印对头,并出队列
q.pop();
if (q.size() > 0)
visitTree(q.front());//递归
}
}
int _tmain(int argc, _TCHAR* argv[])
{
createTree();
visitTree(pTreeRoot);
system("pause");
return 0;
}