zoukankan      html  css  js  c++  java
  • 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 (≤) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N1. Then N lines follow, each corresponds to a node from 0 to N1, 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

    题目大意:给出一颗二叉树, 求他的镜像二叉树的层序遍历和中序遍历; 方法和一般的遍历一样, 只是先遍历右子树再遍历左子树
     1 #include<iostream>
     2 #include<vector>
     3 #include<queue>
     4 using namespace std;
     5 vector<vector<int> > v(10);
     6 vector<int> in, exist(10, 1), level;
     7 
     8 void inOrder(int root){
     9   if(root==-1) return;//先遍历右子树再遍历左子树
    10   if(v[root][1]!=-1) inOrder(v[root][1]);
    11   in.push_back(root);
    12   if(v[root][0]!=-1) inOrder(v[root][0]);
    13 }
    14 
    15 int main(){
    16   int n, i, root, left, right;
    17   char l, r;
    18   scanf("%d", &n);
    19   for(i=0; i<n; i++){
    20     cin>>l>>r;
    21     left = l=='-' ? -1 : l-'0';
    22     right = r=='-' ? -1 : r-'0';
    23     if(left>=0) exist[left]=0;
    24     if(right>=0) exist[right]=0;
    25     v[i].push_back(left); v[i].push_back(right);
    26   }
    27   for(i=0; i<n; i++) if(exist[i]) root=i;
    28   queue<int> q;
    29   q.push(root);
    30   while(q.size()){
    31     int temp=q.front();
    32     q.pop();
    33     level.push_back(temp);
    34     if(v[temp][1]!=-1) q.push(v[temp][1]);
    35     if(v[temp][0]!=-1) q.push(v[temp][0]);
    36   }
    37   inOrder(root);
    38   printf("%d", level[0]);
    39   for(i=1; i<n; i++) printf(" %d", level[i]);
    40   printf("
    %d", in[0]);
    41   for(i=1; i<n; i++) printf(" %d", in[i]);
    42   return 0;
    43 }
     
  • 相关阅读:
    SEO优化范列20120215
    IIS中的上传目录权限设置问题
    c# webservice接口 输出xml
    360浏览器用window.open的话,session会丢失
    iis网站安全设置
    SEO优化20120215
    IIS6.0安全设置方法 .
    优化20120215
    WIN2003的安全设置
    webservice 生成dll的方法
  • 原文地址:https://www.cnblogs.com/mr-stn/p/9539277.html
Copyright © 2011-2022 走看看