L2-006 树的遍历
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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
思路:
中序遍历:左根右
后序遍历:左右跟
根据后序遍历得到根节点,在中序遍历中查找根节点所在的位置,根的左边为左子树根的右边为右子树,因此我们在左子树中用同样的方式进行查找(递归)右子树同理(递归)。
private static Tree creeTree(int pl, int pr, int il, int ir) {
if (pl > pr) {
return null;
}
Tree tree = new Tree();
tree.data = post.get(pr);
int k = in.indexOf(tree.data);
int cha = k - il;
tree.left = creeTree(pl, pl + cha - 1, il, k - 1);
tree.right = creeTree(pl + cha, pr - 1, k + 1, ir);
return tree;
}
进行层次遍历:
需要用到队列存储,存储当前节点,当队列不为空时,将头节点出队,如果当前节点存在左节点将该左节点进队,如果当前节点存在右节点将右节点进队
private static void show(Tree tree) {
LinkedList<Tree> queue = new LinkedList<>();
queue.add(tree);
while (!queue.isEmpty()) {
Tree tr = new Tree();
tr = queue.pop();
str += tr.data + " ";
if (tr.left != null) {
queue.add(tr.left);
}
if (tr.right != null) {
queue.add(tr.right);
}
}
}
最后输出字符串去除末尾空格
完整代码
import java.util.*;
class Tree{
int data;
Tree left;
Tree right;
}
public class Main {
static ArrayList<Integer> post = new ArrayList<>();
static ArrayList<Integer> in = new ArrayList<>();
static String str = "";
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
post.add(sc.nextInt());
}
for (int i = 0; i < n; i++) {
in.add(sc.nextInt());
}
Tree tree = creeTree(0, n - 1, 0, n - 1);
show(tree);
System.out.println(str.trim());
}
private static void show(Tree tree) {
LinkedList<Tree> queue = new LinkedList<>();
queue.add(tree);
while (!queue.isEmpty()) {
Tree tr = new Tree();
tr = queue.pop();
str += tr.data + " ";
if (tr.left != null) {
queue.add(tr.left);
}
if (tr.right != null) {
queue.add(tr.right);
}
}
}
private static Tree creeTree(int pl, int pr, int il, int ir) {
if (pl > pr) {
return null;
}
Tree tree = new Tree();
tree.data = post.get(pr);
int k = in.indexOf(tree.data);
int cha = k - il;
tree.left = creeTree(pl, pl + cha - 1, il, k - 1);
tree.right = creeTree(pl + cha, pr - 1, k + 1, ir);
return tree;
}
}