프로그램 설계 기초 13 반전 트리 방법
3202 단어 pat 세월
The following is from Max Howell @twitter:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can't invert a binary tree on a whiteboard so fuck off.
Now it's your turn to prove that YOU CAN invert a binary tree!
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node from 0 to N−1, and gives the indices of the left and right children of the node. If the child does not exist, a
-
will be put at the position. Any pair of children are separated by a space. Output Specification:
For each test case, print in the first line the level-order, and then in the second line the in-order traversal sequences of the inverted tree. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.
Sample Input:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
Sample Output:
3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1
하나, 반전 두 갈래 나무 쓰기 (물론 이 문제는 반전 두 갈래 나무를 사용하지 않고 입력할 때 반으로 값을 부여한다)
void posOrder(int root) {
if (root == -1) {
return;
}
posOrder(Node[root].lchild);
posOrder(Node[root].rchild);
swap(Node[root].lchild, Node[root].rchild);
}
내 코드
#include
#include
using namespace std;
int N = 0;
int times = 0;
int root = 0;
int flag[15] = { 0 };
struct Node {
int data;
int lchild;
int rchild;
}node[15];
queue que;
void levelOrder(int index) {
while (!que.empty()) {
int front = que.front();
que.pop();
printf("%d", front);
times++;
if (times != N) {
printf(" ");
}
else {
printf("
");
}
if (node[front].lchild != -1)que.push(node[front].lchild);
if (node[front].rchild != -1)que.push(node[front].rchild);
}
}
void inOrder(int index) {
if (index == -1) {
return;
}
inOrder(node[index].lchild);
printf("%d", index);
times++;
if (times != N) {
printf(" ");
}
inOrder(node[index].rchild);
}
int main() {
char a;
char b;
int num_1 = 0;
int num_2 = 0;
scanf("%d", &N);
getchar();
for (int i = 0; i < N; i++) {
node[i].data = i;
node[i].lchild = -1;
node[i].rchild = -1;
}
for (int i = 0; i < N; i++) {
a = getchar();
getchar();
b = getchar();
getchar();
if (a != '-') {
num_1 = a - '0';
node[i].rchild = num_1;
if (flag[num_1] == 0) {
flag[num_1] = 1;
}
}
if (b != '-') {
num_2 = b - '0';
node[i].lchild = num_2;
if (flag[num_2] == 0) {
flag[num_2] = 1;
}
}
}
int k = 0;
for (k = 0; k < N; k++) {
if (flag[k] == 0) {
break;
}
}
root = k;
que.push(root);
levelOrder(root);
times = 0;
inOrder(root);
return 0;
}