1102. Invert a Binary Tree (25)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1102. Invert a Binary Tree (25)相关的知识,希望对你有一定的参考价值。
#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)的主要内容,如果未能解决你的问题,请参考以下文章
1102. Invert a Binary Tree (25)
PAT-1102(Invert a Binary Tree)