当前位置: 代码迷 >> 综合 >> PAT - 甲级 - 1102. Invert a Binary Tree (25)(中序遍历,层次遍历)
  详细解决方案

PAT - 甲级 - 1102. Invert a Binary Tree (25)(中序遍历,层次遍历)

热度:120   发布时间:2023-10-09 15:33:14.0

题目描述:

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

题目思路:

给定一颗二叉树的n个结点编号为0-(n-1)的左右孩子,输出中序遍历和镜像层次遍历的序列。中序遍历可以递归求解,镜像层次遍历只要在bfs中将右孩子先入队左孩子次之即可。

题目代码:

#include <cstdio>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;
struct Node{int l,r;
};vector<Node>v(11);
vector<int>vis(11,0);
vector<int>inorder;
int n;
char s1[2],s2[2];
// 中序遍历 
void dfs(int root){if(v[root].l != -1)dfs(v[root].l);inorder.push_back(root);if(v[root].r != -1)dfs(v[root].r);
}int main(){scanf("%d",&n);// 建树 for(int i = 0; i < n; i++){scanf("%s%s",s1,s2);if(s1[0] != '-'){int temp = s1[0] - '0';if(strlen(s1) == 2)temp = temp * 10 + s1[1] - '0';v[i].r = temp;vis[temp] = 1;}else{v[i].r = -1;}if(s2[0] != '-'){int temp = s2[0] - '0';if(strlen(s2) == 2)temp = temp * 10 + s2[1] - '0';v[i].l = temp;vis[temp] = 1;}else{v[i].l = -1;}}// 寻找根节点int root ;for(int i = 0; i < n; i++){if(!vis[i]){root = i;break;}} // 层次遍历 queue<int>q;q.push(root); while(!q.empty()){int node = q.front();if(node != root) printf(" ");printf("%d",node);if(v[node].l != -1)q.push(v[node].l);if(v[node].r != -1)q.push(v[node].r);q.pop();}printf("\n");dfs(root);for(int i = 0; i < inorder.size() ;i++){if(i != 0)printf(" ");printf("%d",inorder[i]); }return 0;
}


  相关解决方案