ALGO-20 求先序排列

ALGO-20 求先序排列

题目

资源限制

内存限制:256.0MB C/C++时间限制:1.0s Java 时间限制:3.0s Python 时间限制:5.0s

问题描述

给出一棵二叉树的中序与后序排列。求出它的先序排列。(约定树结点用不同的大写字母表示,长度<=8)。

输入格式

两行,每行一个字符串,分别表示中序和后序排列

输出格式

一个字符串,表示所求先序排列

样例输入
   BADC
   BDCA

样例输出

ABCD

代码

import java.util.Scanner;

public class ALGO_20 {
    static StringBuffer str = new StringBuffer();

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String ldr = sc.nextLine();
        String lrd = sc.nextLine();
        sc.close();
        Pre_order(ldr, lrd);
        System.out.println(str.toString());
    }

    private static void Pre_order(String ldr, String lrd) {
        if (ldr.equals(lrd)) {
            str.append(reverse(ldr));
            return;
        }
        char root = lrd.charAt(lrd.length() - 1);
        str.append(root);
        String[] ldr_tree = ldr.split(String.valueOf(root));
        int index = branch(ldr_tree[0], lrd) + 1;
        if (ldr_tree[0].equals(""))// NOTE 左子树为空
            ;
        else if (index == 0)// NOTE 左子树是叶子节点
            str.append(ldr_tree[0]);
        else
            Pre_order(ldr_tree[0], lrd.substring(0, index));
        if (ldr_tree.length == 1)// NOTE 右子树为空
            ;
        else if (index == lrd.length() - 1)// NOTE 右子树是叶子节点
            str.append(ldr_tree[1]);
        else
            Pre_order(ldr_tree[1], lrd.substring(index, ldr.length() - 1));
    }

    /**
     * 翻转字符,单字符也适用
     * @param {String} str
     * @return 翻转结果
     */
    private static StringBuffer reverse(String str) {
        return new StringBuffer(str).reverse();
    }

    /**
     * 找到后序排序的子树分界
     * @param {String} child
     * @param {String} parent
     * @return 左子树最后的索引
     */
    private static int branch(String child, String parent) {
        int index = -1;
        for (int i = 0; i < child.length(); i++) {
            index = Math.max(index, find(child.charAt(i), parent));
        }
        return index;
    }

    /**
     * 找到字符在字符串中的索引
     * @param {Character} c
     * @param {String} str
     * @return 索引
     */
    private static int find(char c, String str) {
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == c) {
                return i;
            }
        }
        return -1;
    }
}

posted @ 2022-04-17 09:28  morning-start  阅读(33)  评论(0编辑  收藏  举报