按層次順序建立和遍歷二叉樹
阿新 • • 發佈:2018-11-24
第一篇部落格,獻給了資料結構--二叉樹。
最近在學資料結構,總結一下二叉樹的按層次建立的方法,希望對此時的你有所幫助~
有錯誤的地方,還望大神指出,或者有其他更好的方法,歡迎留言~
/*利用順序佇列,層次建立二叉樹*/ #include <iostream> using namespace std; #define MAXSIZE 100 struct tnode //樹的資料結構 { int data; tnode *lchild, *rchild; }; struct queue //佇列的資料結構 { tnode *data[MAXSIZE]; int front, rear; }; void creat(queue &q); //建立一個空佇列 void enqueue(queue &q,tnode *t); //將t入隊 tnode *dequeue(queue &q); //出隊,並返回對頭元素 bool isempty(queue &q); //判斷佇列是否為空 tnode *creatbintree(); //按層次順序建立一棵二叉樹,並返回根節點 void showbintree(tnode *root); //層次遍歷二叉樹 int main() { tnode *root = NULL; root = creatbintree(); showbintree(root); system("pause"); return 0; } void creat(queue &q) { q.front = q.rear = 0; } void enqueue(queue &q, tnode *t) { if ((q.rear + 1) % MAXSIZE == q.front) { cout << "棧滿,不能進棧" << endl; return; } q.rear = (q.rear + 1) % MAXSIZE; q.data[q.rear] = t; } tnode *dequeue(queue &q) { tnode *t; q.front = (q.front + 1) % MAXSIZE; t= q.data[q.front]; return t; } bool isempty(queue &q) { return (q.front == q.rear); } tnode *creatbintree() { //1.先將根節點入隊,當佇列不為空時,迴圈執行以下操作: //2.輸入左子樹的值,不為空,將其入隊 //3.輸入右子樹的值,不為空,將其入隊 int a; tnode *root; queue Q; creat(Q); cout << "請輸入節點值以-1表示空節點:" << endl; cin >> a; if (a == -1) //如果第一個節點為空,就直接返回空樹 return NULL; else { root = new tnode; root->data = a; enqueue(Q, root); //根節點入隊 } while (!isempty(Q)) //當佇列不為空 { //先輸入左孩子的值,再輸入右孩子的值 tnode *p= dequeue(Q); cin >> a; if (a == -1) //左孩子為空 p->lchild = NULL; else { p->lchild = new tnode; p->lchild->data = a; enqueue(Q, p->lchild); //左孩子入隊 } cin >> a; if (a == -1) //右孩子為空 p->rchild = NULL; else { p->rchild = new tnode; p->rchild->data = a; enqueue(Q, p->rchild); //右孩子入隊 } } return root; } void showbintree(tnode *root) { //1.先將根節點入隊,當佇列不為空時,迴圈執行以下操作: //2.出隊一個元素,訪問它 //3.若左子樹不為空,將其入隊 //4.若右子樹不為空,將其入隊 queue Q; tnode *p; creat(Q); if (root == NULL) return; enqueue(Q, root); while (!isempty(Q)) { p = dequeue(Q); cout << p->data << ' '; if(p->lchild) enqueue(Q, p->lchild); if(p->rchild) enqueue(Q, p->rchild); } cout << endl; }