UVa 122 - Trees on the level

为什么这个题网上全是用指针建树呢?

虽然刘爷的紫书上标程拿指针写,不过明显这题有更加简单的写法。

根据输入的每个节点的生成路径判断其对应完全二叉树时的编号。

设根节点为1号,左儿子编号为 id << 1 , 右儿子编号为 id << 1 | 1

按照编号大小排序,顺序输出就是层次遍历。

如何判断是否是一棵树?只需要判断某个节点的父亲是否存在、以及当前节点是否重复了即可。

为了方便,给根节点(1号节点)加一个父节点并加入集合。

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <vector>
 4 #include <set>
 5 #define Maxsize 100000+1
 6 using namespace std;
 7 struct node{
 8     int val;
 9     int id;
10     node(string& str){
11         val = 0;
12         id = 1;
13         int pos = (int)str.find(',');
14         int size = (int)str.size();
15         for (int i = 1; i < pos; i++) {
16             val = (val<<1)+(val<<3)+(str[i]^48);
17         }
18         size--;
19         for (int i = pos+1; i < size; i++) {
20             if(str[i]=='L'){
21                 id <<= 1;
22             }else{
23                 id = id<<1|1;
24             }
25         }
26     }
27 };
28 bool comp(const node&a,const node&b){
29     return a.id < b.id;
30 }
31 int main(){
32     string temp;
33     while (cin >> temp) {
34         vector<node> vec;
35         if(temp == "()"){
36             cout << "not complete" << endl;
37             continue;
38         }
39         vec.push_back(node(temp));
40         while (cin >> temp) {
41             if(temp == "()")
42                 break;
43             vec.push_back(node(temp));
44         }
45         sort(vec.begin(),vec.end(),comp);
46         set<int> st;
47         st.insert(0);
48         int flag = 1;
49         for (vector<node> :: iterator it = vec.begin(); it != vec.end(); it++) {
50             if(!st.count(it->id/2) || st.count(it->id)){
51                 flag = 0;
52                 break;
53             }
54             st.insert(it->id);
55         }
56         
57         if(flag){
58             int first = 1;
59             for (vector<node> :: iterator it = vec.begin(); it != vec.end(); it++) {
60                 if(first)
61                     first = 0;
62                 else
63                     cout << ' ';
64                 cout << it->val;
65             }
66             cout << endl;
67         }else{
68             cout << "not complete" << endl;
69         }
70     }
71     return 0;
72 }

 

posted @ 2020-03-20 15:30  popozyl  阅读(455)  评论(0编辑  收藏  举报