1. 程式人生 > >畢業了C++二叉樹層次遍歷

畢業了C++二叉樹層次遍歷

== 容器 null tdi 指針 creat tno bit stack

//代碼經過測試,賦值粘貼即可用
#include<iostream> #include<stdio.h> #include<stack> #include<queue> #include<malloc.h> using namespace std; //二叉樹結點 typedef struct BTNode{ char data; struct BTNode *lchild; struct BTNode *rchild; }BTNode; //模板先序建立二叉樹,大話p187,教科書吧版 BTNode *CreateBiTree()//
只需要一個函數 { char ch; BTNode *T; scanf("%c",&ch); if(ch==#) T=NULL; else { T = (BTNode *)malloc(sizeof(BTNode)); T->data = ch; T->lchild = CreateBiTree(); T->rchild = CreateBiTree(); } return T;//返回根節點 } //層次遍歷 void LevelOrder(BTNode *T){
//queue<BTNode> queue;大bug隱藏在這個地方;註意queue這個容器裝的是什麽東西 queue<BTNode *> queue;
queue.push(T); //算法:根結點入隊列 while(!queue.empty()){ //若隊列非空則循環執行下列的3個步驟 T = queue.front(); //步驟1:對頭元素出隊,指針從新指向,front()方法是將返回隊頭元素 printf("%c ",T->data);//隊頭元素出隊然後將隊頭元素的左右孩子入隊 queue.pop();//
pop是出隊 if(T->lchild != NULL){//步驟2:左子樹不空,將左子樹入隊 queue.push(T->lchild);//入隊的就是一個地址元素 } if(T->rchild != NULL){//步驟3:右子樹不空,將右子樹入隊 queue.push(T->rchild); } } } int main() { BTNode *T; T = CreateBiTree();//建立 LevelOrder(T); return 0; }

畢業了C++二叉樹層次遍歷