zoukankan      html  css  js  c++  java
  • 1102 Invert a Binary Tree (25 分)(二叉树遍历)

    二叉树有N个结点,给出每个结点的左右孩子结点的编号,把二叉树反转(左右孩子交换  所以是后序遍历交换) 输出反转后二叉树的层序遍历和中序遍历

    #include<bits/stdc++.h>
    
    using namespace std;
    const int N=110;
    struct node
    {
        int L,R;
    }s[N];
    int toint(char ch)
    {
        if(ch=='-'){
            return -1;
        }
        else{
            return ch-'0';
        }
    
    }
    int isroot[N];
    void postorder(int root)
    {
        if(root==-1){
            return;
        }
        postorder(s[root].L);
        postorder(s[root].R);
        swap(s[root].L,s[root].R);
    }
    vector<int>in;
    void print(int root)
    {
        if(root!=-1){
            print(s[root].L);
            in.push_back(root);
            print(s[root].R);
        }
    }
    vector<int>le;
    void lever(int root)
    {
        queue<int>Q;
        Q.push(root);
        while(!Q.empty()){
            int u=Q.front();
            Q.pop();
            le.push_back(u);
            if(s[u].L!=-1) Q.push(s[u].L);
            if(s[u].R!=-1) Q.push(s[u].R);
    
        }
    }
    int main()
    {
        fill(isroot,isroot+N,false);
        int n;
        scanf("%d",&n);
        for(int i=0;i<n;i++){
            char ch1,ch2;
            scanf("%*c%c %c",&ch1,&ch2);
            int a=toint(ch1);
            int b=toint(ch2);
            s[i].L=a;
            s[i].R=b;
            isroot[a]=true;
            isroot[b]=true;
        }
        int root=0;
        for(int i=0;i<n;i++){
            if(isroot[i]==false){
                root=i;
            }
        }
        postorder(root);
        print(root);
        lever(root);
        for(int i=0;i<le.size();i++){
            if(i) printf(" ");
            printf("%d",le[i]);
        }
        printf("
    ");
        for(int i=0;i<in.size();i++){
            if(i) printf(" ");
            printf("%d",in[i]);
        }
        printf("
    ");
        return 0;
    }
  • 相关阅读:
    下载安装安卓开发工具
    斐波那契数列
    各位相加
    求连续最大子序列和
    反转字符串中的单词
    统计位数为偶数的数字
    Express框架的整体感知
    node.js当中的http模块与url模块的简单介绍
    formidable处理提交的表单或文件的简单介绍
    30分钟,学会经典小游戏编程!
  • 原文地址:https://www.cnblogs.com/chenchen-12/p/10085025.html
Copyright © 2011-2022 走看看