题目链接
给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数 N
(≤30),是二叉树中结点的个数。第二行给出其中序遍历序列。第三行给出其前序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树反转后的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
1 2 3 4 5 6 7
4 1 3 2 6 5 7
输出样例:
4 6 1 7 5 3 2
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Scanner;
/**
* @Author: Travelmate
* @CreateTime: 2021/2/24 22:26
* @Description:
*/
public class Main {
static int N;
static Scanner sc;
/**
* 层序遍历
* @param root
*/
static void Layers(TreeNode root){
if (root == null) {
return;
}
Queue<TreeNode> q = new ArrayDeque<>();
q.add(root);
int num = 0;
while (!q.isEmpty()) {
TreeNode tmp = q.poll();
if (tmp.left != null) {
q.add(tmp.left);
}
if (tmp.right != null) {
q.add(tmp.right);
}
if (num == 0){
System.out.print(tmp.val);
num++;
}else {
System.out.print(" " + tmp.val);
}
}
}
/**
* 镜面翻转
* @param root
* @return
*/
static TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
invertTree(root.left);
invertTree(root.right);
return root;
}
/**
* 由中序遍历 前序遍历 构造二叉树
* @param in
* @param pre
* @return
*/
static TreeNode buildTree(int[] in, int[] pre){
return build(in, 0, in.length - 1, pre, 0, pre.length -1);
}
static TreeNode build(int[] in, int inStart, int inEnd, int[] pre, int preStart, int preEnd) {
if (inStart > inEnd){
return null;
}
int rootVal = pre[preStart];
int index = 0;
for (int i = inStart; i <= inEnd ; i++) {
if (in[i] == rootVal){
index = i;
break;
}
}
int leftSize = index - inStart;
TreeNode root = new TreeNode(rootVal);
root.left = build(in, inStart, index - 1, pre, preStart + 1, preStart + leftSize);
root.right = build(in, index + 1, inEnd, pre, preStart + leftSize + 1, preEnd);
return root;
}
public static void main(String[] args) {
sc = new Scanner(System.in);
N = sc.nextInt();
//输入中序遍历数组
int[] in = new int[N];
//输入前序遍历数组
int[] pre = new int[N];
for (int i = 0; i < N; i++) {
in[i] = sc.nextInt();
}
for (int i = 0; i < N; i++) {
pre[i] = sc.nextInt();
}
//根据中序遍历 前序遍历 构造二叉树
TreeNode node = buildTree(in, pre);
//镜面翻转
TreeNode Node = invertTree(node);
//层序遍历
Layers(Node);
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val; }
}