1. 程式人生 > >二叉樹的層次遍歷

二叉樹的層次遍歷

http null root fail vector remove ack back input

技術分享

題意:輸入一棵樹,你的任務是從上到下,從左到右輸出各個結點的值,輸入(11,LL)表示結點的值是11,位置是從根節點訪問兩次左子樹。

解題思路:此題需要先構造一棵二叉樹,有兩種方法來表示二叉樹,一是指針表示,而是數組表示。   1.此題在訪問的時候用到了隊列                                                                                  2.

此題在輸入的時候也有一些小技巧,例如,sscanf()函數輸入某個字符串,還有strchr()函數get某些字符,                                                  3.failed標記是否被訪問過                                                                                    4.get一種新的輸出方式 printf("%d%c", ans[i], i == ans.size()-1 ? ‘\n‘ : ‘ ‘);

指針表示:

 1 #include<stdio.h>
 2
#include<string> 3 #include<cstring> 4 #include<queue> 5 #include<vector> 6 #include<iostream> 7 using namespace std; 8 const int MAXX=300; 9 char s[MAXX]; 10 bool failed; 11 12 struct node{ 13 int value; 14 bool have_value; 15 node *left,*right; 16 node():have_value(false
),left(NULL),right(NULL){} 17 }; 18 node* root; 19 20 void addnode(int v,char* s){     //將結點加入樹 21 int n=strlen(s); 22 node* u=root; 23 for(int i=0;i<n;i++){ 24 if(s[i]==L){ 25 if(u->left==NULL) u->left=new node(); 26 u=u->left; 27 } 28 else if(s[i]==R){ 29 if(u->right==NULL) u->right=new node(); 30 u=u->right; 31 } 32 } 33 if(u->have_value) failed=true; 34 u->value=v; 35 u->have_value=true; 36 } 37 38 void remove_tree(node *u){              //釋放內存,防止泄露 39 if(u==NULL) return; 40 remove_tree(u->left); 41 remove_tree(u->right); 42 delete u; 43 } 44 45 bool read_input(){ 46 failed=false; 47 remove_tree(root); //結點的輸入 48 root=new node(); 49 for(;;){ 50 if(scanf("%s",s)!=1) return false; 51 if(!strcmp(s,"()")) break; 52 int v; 53 sscanf(&s[1],"%d",&v); 54 addnode(v,strchr(s,,)+1); 55 } 56 return true; 57 } 58 59 bool bfs(vector<int>& ans){    //廣度優先搜索,從左至右依次找結點 60 queue<node*> q; 61 ans.clear(); 62 q.push(root); 63 while(!q.empty()){ 64 node *u=q.front(); 65 q.pop(); 66 if(!u->have_value) return false; 67 ans.push_back(u->value); 68 if(u->left!=NULL) q.push(u->left); 69 if(u->right!=NULL) q.push(u->right); 70 } 71 return true; 72 } 73 74 int main(){ 75 vector<int> ans; 76 freopen("in.txt","r",stdin); 77 while(read_input()){ 78 // cout<<failed; 79 if(!failed&&bfs(ans)){ 80 for(int i=0;i<ans.size();i++){ 81 printf("%d%c", ans[i], i == ans.size()-1 ? \n : ); 82 83 } 84 } 85 else{ 86 printf("not complete\n"); 87 } 88 } 89 }

二叉樹的層次遍歷