本文主要是介绍从上到下,从左到右输出二叉树的结点,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
输入一颗二叉树,从上到下按层打印树的每个结点,同一层中按照从左往右的顺序打印。
输出 8,6,10,5,7,9,11.
分析:题目为树的层次遍历.(也即图的广度优先遍历)
#include<iostream>
using namespace std;
struct BTreeNode
{
int m_nValue;//value of node
BTreeNode *m_pLeft;//left child of node
BTreeNode *m_pRight;//right child of node
};
BTreeNode *pListIndex;
BTreeNode *pHead;
{
if (!pTreeRoot)
return;
//get a empty queue
deque<BTreeNode*> dequeTreeNode;
//insert the root at the tail of queue
dequeTreeNode.push_back(pTreeRoot);
while (dequeTreeNode.size())
{
//get a node from the head of queue
BTreeNode *pNode = dequeTreeNode.front();
dequeTreeNode.pop_front();
//print the node
cout << pNode->m_nValue << ' ';
//print its left child sub-tree if it has
if (pNode->m_pLeft)
dequeTreeNode.push_back(pNode->m_pLeft);
//print its right child sub-tree if it has
if (pNode->m_pRight)
dequeTreeNode.push_back(pNode->m_pRight);
}
}
//创建二元查找树
void addBTreeNode(BTreeNode*& pCurrent, int value)
{
if (NULL==pCurrent)
{
BTreeNode* pBTree = new BTreeNode();
pBTree->m_pLeft = NULL;
pBTree->m_pRight = NULL;
pBTree->m_nValue = value;
pCurrent = pBTree;
}
else
{
if ((pCurrent->m_nValue) > value)
addBTreeNode(pCurrent->m_pLeft, value);
else if ((pCurrent->m_nValue) < value)
addBTreeNode(pCurrent->m_pRight, value);
}
}
int main()
{
BTreeNode* pRoot = NULL;
pListIndex = NULL;
pHead = NULL;
addBTreeNode(pRoot, 8);
addBTreeNode(pRoot, 6);
addBTreeNode(pRoot, 5);
addBTreeNode(pRoot, 7);
addBTreeNode(pRoot, 10);
addBTreeNode(pRoot, 9);
addBTreeNode(pRoot, 11);
PrintFromTopToBottom(pRoot);
return 0;
}
这篇关于从上到下,从左到右输出二叉树的结点的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!