标签:struct names name use algorithm algo out log pre
#include<iostream> #include<string> #include<map> #include<vector> #include<algorithm> #include<queue> #include<set> #include<stack> using namespace std; struct node { int data; int left=-1, right=-1; }; node arr[11]; int num; void posti(int root) { if (arr[root].left != -1) { posti(arr[root].left); } if (arr[root].right != -1) { posti(arr[root].right); } swap(arr[root].left, arr[root].right); } bool f = 0; void bfs(int root) { queue<int> q; q.push(root); while (!q.empty()) { int temp = q.front(); q.pop(); if (f == 0) { f = 1; cout << temp; } else cout << ‘ ‘ << temp; if (arr[temp].left != -1)q.push(arr[temp].left); if (arr[temp].right != -1)q.push(arr[temp].right); } } bool k = 0; void inorder(int root) { //cout << arr[root].left; if (arr[root].left != -1) { inorder(arr[root].left); } if (k == 0) { cout << root; k = 1; } else cout << ‘ ‘ << root; if (arr[root].right != -1) { inorder(arr[root].right); } } int main() { int isroot[11]; cin >> num; fill(isroot, isroot + 11, 0); for (int i = 0; i < num; i++) { string s1, s2; cin >> s1 >> s2; arr[i].data = i; if (s1 != "-"){ arr[i].left = stoi(s1); isroot[stoi(s1)] = 1; } if (s2 != "-"){ arr[i].right = stoi(s2); isroot[stoi(s2)] = 1; } } int r = 0; for (int i = 0; i < num; i++) { //cout << isroot[i]; if (isroot[i] == 0) { r = i; break; } } //cout << r; posti(r); bfs(r); cout << endl; inorder(r); system("pause"); }
1102. Invert a Binary Tree (25)
标签:struct names name use algorithm algo out log pre
原文地址:http://www.cnblogs.com/wsggb123/p/7279063.html