二叉樹層次輸出帶換行
阿新 • • 發佈:2019-01-22
1. 二叉樹的層次輸出(不帶換行輸出)
思想:利用一個佇列
2. 二叉樹的層次輸出(帶換行輸出)void levelPrint1(BTree *root){ //不帶換行的 if(!root)return; BTree *temp; queue<BTree*> myque; myque.push(root); while(!myque.empty()){ temp = myque.front(); print(temp->val); myque.pop(); if(temp->left)myque.push(temp->left); if(temp->right)myque.push(temp->right); }
思想:要獲得當前行的最後一個結點,以及下一行的最後一個結點
void levelPrint2(BTree *root){ //帶換行輸出 if(!root)return; BTree *thelast = root, *nextlast = root; //thelast表示當前行最後一個結點,nextlast表示下一行的最後一個結點 queue<BTree*> myque; BTree *temp; myque.push(root); while(!myque.empty()){ temp = myque.front(); myque.pop(); print(temp->val); if(temp->left){ myque.push(temp->left); nextlast = temp->left; } if(temp->right){ myque.push(temp->right); nextlast = temp->right; } if(thelast == temp){ //判斷是否到當前行的末尾 print("\n"); //換行 thelast = nextlast; } } }
兄弟夥約我打王者農藥,就沒跑程式了,如有錯誤,歡迎指正,第一篇CSDN部落格,我以後會保持一定的產出,堅持寫下去!