1.后序+中序遍历前序
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2
import java.util.*;
public class ss {
static class treenode {
int val;
treenode left;
treenode right;
treenode(int val) {
this.val = val;
}
}
static int[] houder;
static int[] zhongder;
static List<Integer> result = new ArrayList<>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(); // 读取二叉树中节点的个数
houder = new int[n]; // 存储后序遍历序列的数组
zhongder = new int[n]; // 存储中序遍历序列的数组
// 读取后序遍历序列
for (int i = 0; i < n; i++) {
houder[i] = scanner.nextInt();
}
// 读取中序遍历序列
for (int i = 0; i < n; i++) {
zhongder[i] = scanner.nextInt();
}
treenode root = bulid();
bianli(root);
for (int i = 0; i < result.size(); i++) {
if (i > 0) {
System.out.print(" ");
}
System.out.print(result.get(i));
}
}
// 构建树
public static treenode builetree(int houstart, int houend, int zhonstart, int zhonend) {
if (houstart > houend || zhonstart > zhonend) {
return null;
}
// 后序的最后一个结点(根结点)
int rootval = houder[houend];
// 创建根结点
treenode root = new treenode(rootval);
// 找到根节点的位置
int k = 0;
for (int i = zhonstart; i <= zhonend; i++) {
if (zhongder[i] == rootval) {
k = i;
break;
}
}
// 计算左子树的节点个数
int leftSub = k - zhonstart;
// 递归构建左子树
root.left = builetree(houstart, houstart + leftSub - 1, zhonstart, k - 1);
// 递归构建右子树
root.right = builetree(houstart + leftSub, houend - 1, k + 1, zhonend);
return root;
}
// 根据后序遍历和中序遍历构建二叉树的方法
public static treenode bulid() {
return builetree(0, houder.length - 1, 0, zhongder.length - 1);
}
// 层序遍历
public static void bianli(treenode root) {
if (root == null) {
return;
}
Queue<treenode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
treenode node = queue.poll();
result.add(node.val);
// 如果当前节点的左子节点不为空,将左子节点加入队列
if (node.left != null) {
queue.offer(node.left);
}
// 如果当前节点的右子节点不为空,将右子节点加入队列
if (node.right != null) {
queue.offer(node.right);
}
}
}
}