[劍指offer][面試題23]從上往下列印二叉樹
阿新 • • 發佈:2019-01-25
從上往下打印出二叉樹的每個結點,同一層的結點按照從左到右的順序列印。
#include <iostream> #include <stack> using namespace std; struct Node{ int m_nData; Node *m_pLeft; Node *m_pRight; }; void traverseBinaryTreeByLevel(Node *pRoot) { if (pRoot==NULL){ return; } Node *pNode = NULL; deque<Node*> q; q.push_back(pRoot); while (!q.empty()){ pNode = q.front(); q.pop_front(); cout<<pNode->m_nData<<" "; if (pNode->m_pLeft){ q.push_back(pNode->m_pLeft); } if (pNode->m_pRight){ q.push_back(pNode->m_pRight); } } } int main() { Node *node1 = new Node; node1->m_nData = 1; Node *node2 = new Node; node2->m_nData = 2; Node *node3 = new Node; node3->m_nData = 3; Node *node4 = new Node; node4->m_nData = 4; Node *node5 = new Node; node5->m_nData = 5; Node *node6 = new Node; node6->m_nData = 6; Node *node7 = new Node; node7->m_nData = 7; node1->m_pLeft = node2; node1->m_pRight = node3; node2->m_pLeft = node4; node2->m_pRight = node5; node3->m_pLeft = node6; node3->m_pRight = NULL; node4->m_pLeft = node7; node4->m_pRight = NULL; node5->m_pLeft = NULL; node5->m_pRight = NULL; node6->m_pLeft = NULL; node6->m_pRight = NULL; node7->m_pLeft = NULL; node7->m_pRight = NULL; /* 1 / \ 2 3 / \ / 4 5 6 / 7 */ traverseBinaryTreeByLevel(node1); }