Sicily 1156. Binary tree, sicily1156
Question address: 1156. Binary tree
Ideas:
How can we happily output data in the forward order? We need to store data based on the location when storing data!
At first, I was dumbly crying. I always thought that the first input was the root node (the harm of the example, ah, ah !!!!), The result proves no. So we need to find the root node, so how can we find the root node? I used a vector to store the bottom value and traverse the vector value, set the left and right values of the node as the data of the lower mark as the non-root node, and the rest is the root node.
The Code is as follows:
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].left26 >> 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 }