二叉樹的層次遍曆,二叉樹層次遍曆
題目連結:UVA 122 Tree on the level
輸入一顆二叉樹,你的任務是從上到下,從左至右的順序輸出各個節點的值。每個節點都按照從根節點到它的移動序列給出(L,表示做,R表示右)。在輸入中,每個節點的左括弧和右括弧之間沒有空格,相鄰節點之間用一個空格隔開。每棵樹的輸入用一對空括弧“()”結束。
注意: 如果從根到某個節點的路徑上有的節點沒有在輸入中給出,或者給出超過1次,應當輸出 not complete ,節點個數不超過256.
對應第一組輸入。
範例輸入:
(11,LL) (7,LLL) (8,R)(5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) ()(3,L) (4,R) ()
範例輸出:
5 4 8 11 13 4 7 2 1not complete
大家結合代碼來看吧,有詳細的注釋。
#include<cstdio>#include<iostream>#include<cstdlib>#include<cstring>#include<string>using namespace std;const int maxn = 1500 + 100;struct Node{bool is_value; //是否被賦值過int v; //節點值Node *left ,*right;Node():is_value(0),left(NULL),right(NULL){}};Node* root;Node* newnode(){ return new Node();} //如果申請失敗,返回的是NULLbool failed; //表示是否失敗int ans[maxn],cnt; //儲存節點的數組,和計數器void remove_tree(Node* u){ //釋放記憶體if(u == NULL) return ;remove_tree(u->left);remove_tree(u->right);delete(u);}void addnode(int v, char* s){ //添加節點int nlen = strlen(s);Node* u = root;for(int i = 0; i < nlen; i++){ //從根開始遍曆if(s[i] == 'L'){if(u->left == NULL) u->left = newnode();u = u->left;}else if(s[i] == 'R'){if(u->right == NULL) u->right = newnode();u = u->right;}}if(u->is_value) failed = true; //如果已經賦值 ,標記failed u->v = v;u->is_value = true;}bool input_tree(){char s[maxn];failed = false;root = newnode();for(;;){if(scanf("%s",s) !=1 ) return false;if(!strcmp(s,"()"))break;int v;sscanf(&s[1],"%d",&v); //從(後面的數字開始讀取, 將數字讀取到v;addnode(v,strchr(s,',')+1); //這裡體現了字元數組的方便, 指向字元的指標可以直接看做字串,從該位置開始到'\0' //strchr返回字串中 所尋找字元位置的指標,也就是返回 “,” 後面的字串}return true;}bool bfs(){ //隊列實現二叉樹的層序遍曆Node *q[maxn] , *u; //用數組類比隊列q[0] = root;int front = 0, rear = 1;while(front < rear){u = q[front++];if(!u->is_value) return false;ans[cnt++] = u->v; //將頭結點加入ans 或者輸出if(u->left != NULL) q[rear++] = u->left; //將子節點排入佇列if(u->right != NULL) q[rear++] = u->right;}return true;} int main(){while(1){cnt = 0;if(!input_tree()) break;if(!failed && bfs()){for(int i = 0;i < cnt; i++){if(i) printf(" ");printf("%d",ans[i]);}printf("\n");}else{printf("not complete\n");}remove_tree(root);}return 0;}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。