這篇文章主要介紹了C++非遞歸隊(duì)列實(shí)現(xiàn)二叉樹的廣度優(yōu)先遍歷,實(shí)例分析了遍歷二叉樹相關(guān)算法技巧,并附帶了兩個(gè)相關(guān)算法實(shí)例,需要的朋友可以參考下
本文實(shí)例講述了C++非遞歸隊(duì)列實(shí)現(xiàn)二叉樹的廣度優(yōu)先遍歷。分享給大家供大家參考。具體如下:
廣度優(yōu)先非遞歸二叉樹遍歷(或者說層次遍歷):
- void widthFirstTraverse(TNode* root) {
- queue<TNode*> q; // 隊(duì)列
- q.enqueue(root);
- TNode* p;
- while(q.hasElement()) {
- p = q.dequeue(); // 隊(duì)首元素出隊(duì)列
- visit(p); // 訪問p結(jié)點(diǎn)
- if(p->left)
- q.enqueue(p->left);
- if(p->right)
- q.enqueue(p->right);
- }
- }
附帶兩個(gè)相關(guān)示例:
1. 遞歸先序遍歷二叉樹
- void preTraverse(TNode* root) {
- if(!root)
- return;
- visit(root);
- preTraverse(root->left);
- preTraverse(root->Right);
- }
2. 非遞歸先序遍歷二叉樹
- void preTraverseNonRecursive(TNode* root) {
- stack<TNode> stack; // 棧
- stack.push(root);
- TNode* p;
- while(!stack.isEmpty()) { // 棧非空
- p = stack.pop();
- visit(p);
- if(p->pRight)
- s.push(p->pRight);
- if(p->pLeft)
- s.push(p->pLeft);
- }
- }
希望本文所述對(duì)大家的C++程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答