題目地址:1156. Binary tree
思路:
如何愉快地前序輸出呢,要在存儲數據的時候根據位置來存放數據!
一開始被自己蠢哭,一直以為第一個輸入的就是根結點(例子的禍害呀啊啊啊!!!!),結果證明不是的,所以呢,我們要找出根結點,那麼怎麼找根結點呢,我用了一個向量來存儲下標值,遍歷向量值,把節點的左右值作為下標的那個數據設為非根結點,然後剩下的那個就是根節點了。
具體代碼如下:
1 #include <iostream>
2 #include <vector>
3 using namespace std;
4
5 struct Store{
6 char node;
7 int left;
8 int right;
9 bool is_root;
10 }store[1001];
11
12 void print(int x) {
13 if (x == 0) return;
14 cout << store[x].node;
15 print(store[x].left);
16 print(store[x].right);
17 }
18 int main() {
19 int t;
20 while (cin >> t) {
21 int index;
22 vector<int> store_index;
23 for (int i = 0; i < t; i++) {
24 cin >> index;
25 cin >> store[index].node >> store[index].left
26 >> store[index].right;
27 store[index].is_root = true;
28 store_index.push_back(index);
29 }
30 for (int i = 0; i < t; i++) {
31 int left = store[store_index[i]].left;
32 int right = store[store_index[i]].right;
33 store[left].is_root = false;
34 store[right].is_root = false;
35 }
36 int root_node;
37 for (int i = 0; i < t; i++) {
38 if (store[store_index[i]].is_root == true) {
39 root_node = store_index[i];
40 break;
41 }
42 }
43 print(root_node);
44 cout << endl;
45 }
46
47 return 0;
48 }