BFS 层次遍历 静态数组方式创建二叉树

  1 /*输入一颗二叉树,你的任务是按从上到下,从左到右的顺序输出各个结点的值.每个结点都按照从根结点到它的移动序列给出(L表示左,R表示右).在输入中,每个结点的左括号和右括号之间没有空格,相邻结点之间用一个空格隔开.每棵树的输入用一堆空口号()结束(这对括号本身不代表一个结点)
  2 
  3 样例输入:(11,LL) (7,LLL) (8,R) (5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) ()
  4 
  5 (3,L) (4,R) ()
  6 
  7 样例输出:
  8 
  9 5 4 8 11 13 4 7 2 1
 10 
 11 -1
 12 
 13 AC代码如下:*/
 14 
 15 #include <iostream> 
 16 #include <string> 
 17 #include <sstream>  
 18 using namespace std ; 
 19 const int MAXN = 256 ; 
 20 const int root = 1 ;  
 21 int cnt , vis[MAXN] , val[MAXN] , Left[MAXN] , Right[MAXN] ; 
 22 int NewNode()
 23 { 
 24  int u = ++cnt ; 
 25  Left[u] = Right[u] = 0 ; 
 26  return u ; 
 27 }  
 28 void NewTree() 
 29 { 
 30  Left[root] = Right[root] = 0 ; 
 31  cnt = root ; 
 32 } 
 33 int failed ; 
 34 void AddNode(int value , string word) 
 35 { 
 36  int u = root ; 
 37  for (size_t i = 0 ; i < word.size() ; i ++) 
 38  { 
 39   if (word.at(i) == 'L') 
 40   { 
 41    if (!Left[u]) 
 42    { 
 43     Left[u] = NewNode() ;  
 44    } 
 45    u = Left[u] ; 
 46   } 
 47   else if (word.at(i) == 'R') 
 48   { 
 49    if (!Right[u]) 
 50    { 
 51     Right[u] = NewNode() ;  
 52    } 
 53    u = Right[u] ; 
 54   } 
 55  } 
 56  if (vis[u]) 
 57  { 
 58   failed = 1 ; 
 59  } 
 60  val[u] = value ; 
 61  vis[u] = 1 ; 
 62 } 
 63  
 64 int Input_Read() 
 65 { 
 66  cnt = 0 ;  
 67  memset(vis,0,sizeof(vis)) ;    
 68  
 69  failed = 0 ; 
 70  NewTree() ; 
 71  string word ; 
 72  while (true) 
 73  { 
 74   cin >> word ; 
 75   if (cin.eof()) 
 76   { 
 77    return 0 ; 
 78   } 
 79   if (word == "()") 
 80   { 
 81    break ; 
 82   } 
 83   stringstream sin(word) ; 
 84   int tmp ; 
 85   sin.ignore(1) ; 
 86   sin >> tmp ; 
 87   AddNode(tmp,strchr(word.c_str(),',')+1) ; 
 88  } 
 89  return 1 ; 
 90 }  
 91  
 92 int n = 0 , ans[MAXN] ; 
 93  
 94 int bfs() 
 95 { 
 96  int front = 0 , rear = 1 ; 
 97  int q[MAXN] ; 
 98  q[0] = root ; 
 99  memset(ans,0,sizeof(ans)) ; 
100  
101  while (front < rear) 
102  { 
103   int u = q[front++] ; 
104   if (!vis[u]) 
105   { 
106    return 0 ; 
107   } 
108   ans[n++] = val[u] ; 
109   if (Left[u]) 
110   { 
111    q[rear++] = Left[u] ; 
112   } 
113   if (Right[u]) 
114   { 
115    q[rear++] = Right[u] ; 
116   } 
117  } 
118  return 1 ; 
119 } 
120  
121 int main() 
122 { 
123  
124  while (Input_Read()) 
125  { 
126   
127   if (!bfs()) 
128   { 
129    failed = 1 ; 
130   } 
131   if (failed) 
132   { 
133    cout << -1 << endl ; 
134   } 
135   else { 
136    for (int i = 0 ; i < n ; ++ i) 
137    { 
138      cout << ans[i] << " " ; 
139    } 
140    cout << endl ; 
141   } 
142  }  
143  
144  return 0 ; 
145 } 
View Code

 

posted on 2013-07-10 23:16  Forgiving  阅读(162)  评论(0编辑  收藏  举报