通过一个二叉树的后序,中序遍历求出前序遍历

import java.util.Scanner;

/**
 * @PackageName: PACKAGE_NAME
 * @ClassName: Main
 * @Author: fan
 * @Date: 2019/12/13 14:02
 * @Description:
 */

//二叉树已知后续和中序数列,求前序数列
public class Main {
    static int arrfirst[] = new int[30];
    static int point = 0;
    public  static void getArrfirst(int arrl[],int arrm[]){
        //获取根节点
        if (arrl.length == 0 )return;
        int root = arrl[arrl.length-1];
        arrfirst[point++]= root;
        if (arrl.length == 1)return;

        int rootindex=0;
        for (int i = 0; i < arrm.length; i++) {
            if (root == arrm[i]){
                rootindex = i;
                break;
            }
        }
        int arrleft[] = new int[rootindex];
        int arrright[] = new int[arrm.length-rootindex-1];
        for (int i = 0; i < arrm.length; i++) {
            if (i < rootindex){
                arrleft[i] = arrm[i];
            }else if(i > rootindex){
                arrright[i-1-rootindex] = arrm[i];
            }
        }
        int arrLl[] = new int[rootindex];
        int arrRl[] = new int[arrm.length-rootindex-1];
        int j = 0;
        for (int i = 0; i < arrLl.length; i++) {
            arrLl[i] = arrl[j++];
        }
        for (int i = 0; i < arrRl.length; i++) {
            arrRl[i] = arrl[j++];
        }
        getArrfirst(arrLl,arrleft);
        getArrfirst(arrRl,arrright);
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int length = sc.nextInt();
        int arrlast[] = new int[length];
        int arrmid[] = new int[length];
        for (int i = 0; i < arrlast.length; i++) {
                arrlast[i] = sc.nextInt();
        }
        for (int i = 0; i < arrmid.length; i++) {
            arrmid[i] = sc.nextInt();
        }
        getArrfirst(arrlast,arrmid);

        System.out.print("Preorder:");
        for (int i = 0; i <length; i++) {
            System.out.print(arrfirst[i]);
            if (i!=length)System.out.print(" ");
        }
    }
}
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
Preorder: 4 1 3 2 6 5 7
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值