1102. Invert a Binary Tree (25)

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
复制代码
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 15;
struct node{
    int lchild,rchild;
}Node[maxn];
bool isRoot[maxn] = {false};
int n,num = 0; 

void print(int i){
    printf("%d",i);
    num++;
    if(num < n)printf(" ");
    else printf("\n");
}
void inOrder(int root){
    if(root == -1) return;
    inOrder(Node[root].lchild);
    print(root);
    inOrder(Node[root].rchild);
} 
void BFS(int root){
    queue<int> q;
    q.push(root);
    while(!q.empty()){
        int now = q.front();
        q.pop();
        print(now);
        if(Node[now].lchild != -1) q.push(Node[now].lchild);
        if(Node[now].rchild != -1) q.push(Node[now].rchild);
    }
}
void postOrder(int root){
    if(root == -1) return;
    postOrder(Node[root].lchild);
    postOrder(Node[root].rchild);
    swap(Node[root].lchild,Node[root].rchild);
}
int findRoot(){
    for(int i = 0; i < n; i++){
        if(isRoot[i] == false) return i;
    }
}
int strToint(char c){
    if(c == '-') return -1;
    else{
        isRoot[c - '0'] = true;
        return c - '0';
    }
}
 int main(){
  char lchild,rchild;
  scanf("%d",&n);
  for(int i = 0; i < n; i++){
      scanf("%*c%c %c",&lchild,&rchild);
      Node[i].lchild = strToint(lchild);
      Node[i].rchild = strToint(rchild);
  }
  int root = findRoot();
  postOrder(root);
  BFS(root);
  num = 0;//全局定义初始化的值已经在层序遍历的时候加过了 
  inOrder(root);
  return 0;
}
复制代码

 

posted @   王清河  阅读(129)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示