PAT 1099. Build A Binary Search Tree (30)
题目地址: http://www.patest.cn/contests/pat-a-practise/1099
单纯的数据结构题目
想到中序遍历的BST是有序的, 中序插入数, 层序遍历输出就可以了,这个题目为什么是30分呢, 纳闷
1 #include<cstdio> 2 #include<iostream> 3 #include<queue> 4 #include<algorithm> 5 6 using namespace std; 7 8 const int MAX_NODES = 1000; 9 struct Node { 10 int lchild; 11 int rchild; 12 int num; 13 } nodes[MAX_NODES]; 14 int len = 0; 15 16 int nums[MAX_NODES]; 17 int num_index = 0; 18 void in_order(int root) { 19 if (root != -1) { 20 in_order(nodes[root].lchild); 21 nodes[root].num = nums[num_index++]; 22 in_order(nodes[root].rchild); 23 } 24 } 25 26 queue<int> q; 27 void level_order(int root) { 28 num_index = 0; 29 while(!q.empty()) q.pop(); //我不知道怎么清空队列, 只能这样了, 哈哈 30 q.push(root); 31 while(!q.empty()) { 32 int x = q.front(); 33 q.pop(); 34 nums[num_index++] = nodes[x].num; 35 if (nodes[x].lchild != -1) 36 q.push(nodes[x].lchild); 37 if (nodes[x].rchild != -1) 38 q.push(nodes[x].rchild); 39 } 40 } 41 42 void debug_print() { 43 cout << "===============debug==========================" << endl; 44 for (int i = 0; i < len; ++i) { 45 cout << nodes[i].num << endl; 46 } 47 cout << "================debug end =====================" << endl; 48 } 49 50 int main() { 51 while(cin >> len) { 52 for (int i = 0; i < len; ++i) { 53 cin >> nodes[i].lchild >> nodes[i].rchild; 54 } 55 for (int i = 0; i < len; ++i) { 56 cin >> nums[i]; 57 } 58 sort(nums, nums + len); 59 in_order(0); 60 //debug_print(); 61 //cout << "post_order done" << endl; 62 level_order(0); 63 //cout << "level_order done" << endl; 64 cout << nums[0]; 65 for (int i = 1; i < len; ++i) { 66 cout << " " << nums[i]; 67 } 68 cout << endl; 69 } 70 return 0; 71 }

浙公网安备 33010602011771号