• 算法学习(5)----二叉树前序、中序、后序遍历互相转换


    代码:

    #include <iostream>
    using namespace std;
    
    void BinaryTreeFromInOrderAndPreOrderToPostOrder(char InOrder[],char PreOrder[],int length)
    {
        if(length<=0){
            return;
        }
        int rootIndex=0;
        for(;rootIndex<length;rootIndex++){
            if(InOrder[rootIndex]==PreOrder[0])
                break;
        }
        BinaryTreeFromInOrderAndPreOrderToPostOrder(InOrder,PreOrder+1,rootIndex);
        BinaryTreeFromInOrderAndPreOrderToPostOrder(InOrder+rootIndex+1,PreOrder+rootIndex+1,length-rootIndex-1);
        cout<<PreOrder[0];
    }
    
    void BinaryTreeFromInOrderAndPostOrderToPreOrder(char InOrder[],char PostOrder[],int length)
    {
        if(length<=0){
            return ;
        }
        int rootIndex=0;
        for(;rootIndex<length;rootIndex++){
            if(InOrder[rootIndex]==PostOrder[length-1])
                break;
        }
        cout<<PostOrder[length-1];
        BinaryTreeFromInOrderAndPostOrderToPreOrder(InOrder,PostOrder,rootIndex);
        BinaryTreeFromInOrderAndPostOrderToPreOrder(InOrder+rootIndex+1,PostOrder+rootIndex,length-rootIndex-1);
    }
    
    int main(int argc,char* argv[])
    {
        char pre[]="GDAFEMHZ";
        char in[]="ADEFGHMZ";
        char post[]="AEFDHZMG";
        cout<<"The original strings are:
    ";
        cout<<"Pre:"<<pre<<endl
            <<"In:"<<in<<endl
            <<"Post:"<<post<<endl;
    
        cout<<"From InOrder And PreOrder To PostOrder:
    ";
        BinaryTreeFromInOrderAndPreOrderToPostOrder(in,pre,8);
        cout<<endl;
        cout<<"From InOrder And PostOrder To PreOrder:
    ";
        BinaryTreeFromInOrderAndPostOrderToPreOrder(in,post,8);
        cout<<endl;
        return 0;
    }
  • 相关阅读:
    Windows常用命令
    路由器命令基础使用
    《计算机网络》-CCNA命令大全
    Cisco 2960交换机配置
    vscode使用技巧
    Luogu 3321 [SDOI2015]序列统计
    Luogu 3702 [SDOI2017]序列计数
    CF 990 Educational Codeforces Round 45
    Luogu 4705 玩游戏
    CF 438E The Child and Binary Tree
  • 原文地址:https://www.cnblogs.com/dongling/p/5723561.html
Copyright © 2020-2023  润新知