从上到下,从左到右输出二叉树的结点

题目:

输入一颗二叉树,,从上到下按层打印树的每个结点,同一层中按照从左往右的顺序打印。

输出 8,6,10,5,7,9,11.

分析:题目为树的层次遍历.(也即图的广度优先遍历)

#include<deque>#include<iostream>using namespace std;struct BTreeNode{int m_nValue;//value of nodeBTreeNode *m_pLeft;//left child of nodeBTreeNode *m_pRight;//right child of node};BTreeNode *pListIndex;

BTreeNode *pHead;

void PrintFromTopToBottom(BTreeNode* pTreeRoot){if (!pTreeRoot)return;//get a empty queuedeque<BTreeNode*> dequeTreeNode;//insert the root at the tail of queuedequeTreeNode.push_back(pTreeRoot);while (dequeTreeNode.size()){//get a node from the head of queueBTreeNode *pNode = dequeTreeNode.front();dequeTreeNode.pop_front();//print the nodecout << pNode->m_nValue << ‘ ‘;//print its left child sub-tree if it hasif (pNode->m_pLeft)dequeTreeNode.push_back(pNode->m_pLeft);//print its right child sub-tree if it hasif (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;}

每个人在他的人生发轫之初,总有一段时光,

从上到下,从左到右输出二叉树的结点

相关文章:

你感兴趣的文章:

标签云: