2020年西山居Java笔试题
当初参加西山居时候第一道算法题,一直想做来着,给耽误了,补上
给定一个二叉树的前序遍历和中序遍历的序列,输出对应这个二叉树的后续遍历序列。
输入描述:
输入为一行。
两个字符串,分别表示二叉树的前序遍历和中序遍历结果,用空格分隔。保证数据合法
输出描述:
对应输出后序遍历序列
示例1
输入
ABDEC DBEAC
输出
DEBCA
思路:先根据先序、中序序列建立二叉树,然后后序遍历
package 杂题汇总;
import java.util.Scanner;
/**
* @author :Empirefree
* @description:TODO
* @date :2021/1/19 10:25
*/
public class PreAndMid {
public static class TreeNode {
char val;
TreeNode left;
TreeNode right;
TreeNode(char x) { val = x; }
}
/*
* 2020年西山居Java笔试题--先序中序构建二叉树并求后序
*
* Case:ABDEC DBEAC 输出:DEBCA
* */
//TODO:数组传递,类传递
//TODO:static final
public static TreeNode createTreeNode(char[] preChar, int preStart, int preEnd, char[] midChar, int midStart, int midEnd){
if (preStart >= preEnd || midStart >= midEnd) return null;
TreeNode rootNode = new TreeNode(preChar[preStart]);
for (int i = midStart; i < midEnd; i++) {
if (preChar[preStart] == midChar[i]){
int midPreLen = i - midStart;
rootNode.left = createTreeNode(preChar, preStart + 1, preStart + 1 + midPreLen, midChar, midStart, i);
rootNode.right = createTreeNode(preChar, preStart + 1 + midPreLen, preEnd, midChar, i + 1, midEnd);
}
}
return rootNode;
}
public static void postTravel(TreeNode rootTree){
if (rootTree != null){
postTravel(rootTree.left);
postTravel(rootTree.right);
System.out.print(rootTree.val);
}
}
public static void main(String[] args) {
//1、数据输入
final Scanner scanner = new Scanner(System.in);
char[] preChar = scanner.nextLine().toCharArray();
char[] midChar = scanner.nextLine().toCharArray();
//2、构建二叉树
TreeNode rootTree = createTreeNode(preChar, 0, preChar.length, midChar, 0, midChar.length);
//3、后序输出
postTravel(rootTree);
}
}