03-树2. List Leaves (25)
来源:互联网 发布:步兵升级数据 编辑:程序博客网 时间:2024/05/30 05:13
http://www.patest.cn/contests/mooc-ds/03-%E6%A0%912
/*并查集 和 树的递归遍历找叶子节点*/#include <cstdio> #include <sstream> #include <cstring> #include <iostream>#include <string>#include <vector>#include <queue>#include <algorithm>#include <sstream>#include <cmath>#include <stack>using namespace std;#define N 11int n;struct mydata{ int no; int left; int right;};typedef struct node{ int data; struct node* left; struct node* right; node(int _data){ data = _data; left = NULL; right = NULL; }}Bnode;//int str2int(string s)//{// if (s == "-")// return -1;// stringstream ss;// ss << s;// int tmp;// ss >> tmp;// return tmp;//}mydata a[N];int father[N];int find(int x){ if (x == father[x]) return x; return father[x] = find(father[x]);}void merge(int x, int y){ father[find(y)] = find(x);}Bnode* root;Bnode* createtree(Bnode* root ,int rootNum){ if (rootNum == -1) return NULL; root = new node(rootNum); if (a[rootNum].left == -1) { root->left = NULL; } else{ root->left = createtree(root->left, a[rootNum].left); } if (a[rootNum].right == -1) { root->right = NULL; } else{ root->right = createtree(root->right, a[rootNum].right); } return root;}vector<int> v;void inorder(Bnode* root){ queue<Bnode*> que; que.push(root); while (!que.empty()) { Bnode* bt = que.front(); que.pop(); if (bt->left == NULL && bt->right == NULL) v.push_back(bt->data); else { if (bt->left != NULL) { que.push(bt->left); } if(bt->right != NULL) { que.push(bt->right); } } }}int main(){ //freopen("in", "r", stdin); scanf("%d\n", &n); int i; for (i = 0; i < n; i++) { father[i] = i; } mydata dt; char c1, c2; for (i = 0; i < n; i++) { scanf("%c %c\n", &c1, &c2); dt.no = i; if (c1 == '-') { dt.left = -1; } else{ dt.left = (int)(c1 - '0'); if (find(i) != find(dt.left)) { merge(i, dt.left); } } if (c2 == '-') { dt.right = -1; } else{ dt.right = (int)(c2 - '0'); if (find(i) != find(dt.right)) { merge(i, dt.right); } } a[i] = dt; } int rootNum = find(0); root = NULL; root = createtree(root, rootNum); inorder(root); int len = v.size(); printf("%d", v[0]); for (i = 1; i < len; i++) { printf(" %d", v[i]); } printf("\n"); return 0;}
0 0
- 03-树2. List Leaves (25) Java
- 03-树2. List Leaves(25)
- 03-树2. List Leaves (25)
- 03-树2. List Leaves (25)
- 03-树2. List Leaves (25)
- 03-2. List Leaves (25)
- 03-树2. List Leaves
- 03-树2. List Leaves
- 03-2. List Leaves (25) 树的层次遍历
- PAT 数据结构 03-树2. List Leaves (25)
- 03-树2. List Leaves (25) Python C
- PAT 03-2. List Leaves (25)
- PAT 03-2. List Leaves (25)
- 03-树1. List Leaves (25)
- 03-树1. List Leaves (25)
- 03-树1. List Leaves (25)
- 03-树1. List Leaves (25)
- 03-树1. List Leaves (25)
- Fragment相关
- iPhone 如何添加横屏代码
- C#自动更换IE代理IP并判断代理是否可连接网络
- Android中ListView使用addHeaderView和addFooterView注意事项
- 你应该掌握的七种回归技术
- 03-树2. List Leaves (25)
- Spring bean reference example
- 个人发展职业定位思考
- POJ 3041 Asteroids(匈牙利算法模板)
- DialogFragment的使用+j接口回调
- HDU 1248:寒冰王座【Floyd & 完全背包】
- remove all the same elements
- 解析XML
- 获取设备唯一标识码