1102. Invert a Binary Tree (25)

来源:互联网 发布:手机淘宝店标怎么上传 编辑:程序博客网 时间:2024/06/11 12:54

1102. Invert a Binary Tree (25)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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:
81 -- -0 -2 7- -- -5 -4 6
Sample Output:
3 7 2 6 4 0 5 16 5 7 4 3 2 0 1


思路:题意是将一个二叉树反转后(左右子树交换),分别按层序遍历和中序遍历输出
首先可以用结构体数组构造一个二叉树,数组的下标对应每个根结点,然后找出整个二叉树的根结点。最后利用后序遍历进行反转





#include<stdio.h>#include<stdlib.h> #include<math.h>#include<string.h>#include<algorithm>#include <vector> #include<stack> #include <queue>  #include<map>#include<iostream>  #include <functional> #define MAX 101#define MAXD 10001#define TELNUM 10using namespace std;struct Node{int left;int right; }node[MAX];int n,count2 = 0;bool visit[MAX] = {false};void in(int root)/*中序遍历输出*/{if(root == -1){return;}in(node[root].left);printf("%d",root);count2++;if(count2 < n){printf(" ");}in(node[root].right);}void BFS(int root)/*层序遍历输出*/{queue<int> q;q.push(root);int count1 = 0;while(!q.empty()){int temp = q.front();q.pop();printf("%d",temp);count1++;if(count1 < n){printf(" ");}if(node[temp].left != -1) q.push(node[temp].left);if(node[temp].right != -1) q.push(node[temp].right);}printf("\n");}void exchange(int root)/*利用后序遍历交换左右子树*/{if(root == -1){return;}exchange(node[root].left);exchange(node[root].right);int t;t = node[root].left;node[root].left = node[root].right;node[root].right = t;}void findroot(){for(int i = 0; i < n; i++){if(node[i].left != -1){visit[node[i].left] = true;}if(node[i].right != -1){visit[node[i].right] = true;}}}int strchange(char c)/*转换字符*/{if(c == '-'){return -1;}else{return c - '0';}}int main(void){char rnode,lnode;scanf("%d",&n);getchar();/*接收换行符*/for(int i = 0; i < n; i++){scanf("%c %c",&lnode,&rnode);getchar();node[i].left = strchange(lnode);node[i].right = strchange(rnode);}findroot();int root;for(int i = 0; i < n; i++)/*找出根结点*/{if(visit[i] == false){root = i;break;}}exchange(root);/*交换*/BFS(root);in(root);return 0;}


0 0
原创粉丝点击