題目:輸入一顆二元樹,從上往下按層列印樹的每個結點,同一層中按照從左往右的順序列印。
阿新 • • 發佈:2019-02-13
題目:
輸入一顆二元樹,從上往下按層列印樹的每個結點,同一層中按照從左往右的順序列印。
例如輸入
8
/ \
6 10
/ \ / \
5 7 9 11
輸入一顆二元樹,從上往下按層列印樹的每個結點,同一層中按照從左往右的順序列印。
例如輸入
8
/ \
6 10
/ \ / \
5 7 9 11
輸出8 6 10 5 7 9 11。
解題思路:利用佇列先進先出(FIFO)的性質,取出隊首元素,輸出隊首節點元素,將節點的左右子節點加入佇列,取出隊首元素,重複上述操作,直到取出佇列中所有元素。
#include <queue> #include <iostream> #include <string.h> using namespace std; struct BSTreeNode //a node in the binary search tree (BST) { int m_nValue; //value of node BSTreeNode *m_pLeft; // left child of node BSTreeNode *m_pRight; // right child of node }; queue<BSTreeNode*>P; void BuildTree(BSTreeNode *&Node,int n) //建立二叉樹 { if(Node == NULL) { BSTreeNode *NewNode = new BSTreeNode(); NewNode->m_nValue = n; NewNode->m_pLeft = NULL; NewNode->m_pRight = NULL; Node = NewNode; } else if(Node->m_nValue < n) { BuildTree(Node->m_pRight,n); } else { BuildTree(Node->m_pLeft,n); } } void OutPut() { if(P.front() == NULL) return ; BSTreeNode *Node = P.front(); cout<<P.front()->m_nValue<<" "; P.push(P.front()->m_pLeft); P.push(P.front()->m_pRight); P.pop(); OutPut(); } int main() { BSTreeNode *Node = NULL; BuildTree(Node,8); BuildTree(Node,6); BuildTree(Node,10); BuildTree(Node,5); BuildTree(Node,7); BuildTree(Node,9); BuildTree(Node,11); P.push(Node); OutPut(); cout<<endl; return 0; }