zoukankan      html  css  js  c++  java
  • Tree Recovery (UVa 536) 递归遍历二叉树

    题目:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=839&page=show_problem&problem=477

    思路:根据先序遍历和中序遍历建树,再输出下后序遍历即可

    /* Tree Recovery (UVa 536) */
    #include <iostream>
    #include <cstring>
    using namespace std;
    
    const int maxn = 30;
    
    char preOrder[maxn], inOrder[maxn];        //先序遍历、中序遍历 
    char lch[maxn], rch[maxn];                //左结点、右结点
    
    char build(int L1, int R1, int L2, int R2);
    void output(char c);
    
    int main(){
        //freopen("input.txt", "r", stdin);
        while(cin >> preOrder >> inOrder){
            memset(lch, 0, sizeof(lch));
            memset(rch, 0, sizeof(rch));
            build(0, strlen(preOrder)-1, 0, strlen(inOrder)-1);
            output(preOrder[0]);
            cout << endl;
        }
        return 0;
    }
    
    char build(int L1, int R1, int L2, int R2){
        if(L1 > R1 || L2 > R2)
            return 0;
        int mid;
        for(int i=L2; i<=R2; i++){
            if(inOrder[i] == preOrder[L1]){
                mid = i;
                break;
            }
        }
        
        lch[preOrder[L1]-'A'] = build(L1+1, L1+(mid-L2), L2, mid-1);
        rch[preOrder[L1]-'A'] = build(L1+(mid-L2)+1, L1-L2+R2, mid+1, R2);
        
        return preOrder[L1];
    }
    
    void output(char c){
        if(c == 0)
            return ;
        int index = c - 'A';
        output(lch[index]);
        output(rch[index]);
        
        cout << c;    
    }
  • 相关阅读:
    Ubuntu+Mac使用飞鸽传书iptux进行互通
    Mac下查看端口占用
    Ubuntu查看端口占用情况
    Ubuntu桌面卡死时的处理
    Bluefish
    响应式Spring Cloud初探
    go
    INSERT ... ON DUPLICATE KEY UPDATE产生death lock死锁原理
    现在的Unix时间戳(Unix timestamp)
    Android 一款Loading动画的实现思路
  • 原文地址:https://www.cnblogs.com/lighter-blog/p/6028340.html
Copyright © 2011-2022 走看看