题目
“侧影”就是从左侧或者右侧去观察物体所看到的内容。例如上图中男生的侧影是从他右侧看过去的样子,叫“右视图”;女生的侧影是从她左侧看过去的样子,叫“左视图”。
520 这个日子还在打比赛的你,也就抱着一棵二叉树左看看右看看了……
我们将二叉树的“侧影”定义为从一侧能看到的所有结点从上到下形成的序列。例如下图这棵二叉树,其右视图就是 { 1, 2, 3, 4, 5 },左视图就是 { 1, 6, 7, 8, 5 }。
输入格式:
输入第一行给出一个正整数 N (≤20),为树中的结点个数。随后在两行中先后给出树的中序遍历和后序遍历序列。树中所有键值都不相同,其数值大小无关紧要,都不超过 int 的范围。
输出格式:
第一行输出右视图,第二行输出左视图,格式如样例所示。
输入样例:
8
6 8 7 4 5 1 3 2
8 5 4 7 6 3 2 1
输出样例:
R: 1 2 3 4 5
L: 1 6 7 8 5
思路
- 通过中序、后序遍历序列构造二叉树
- 层序遍历构建好的二叉树,用两个容器分别记录每一层第一个节点值以及最后一个节点
构建二叉树
🚨难点🚨
构建过程中最容易出错的就是 确定 构建子树使用的中序、后序数组
,很容易抛出数组下标越界错误。
这里简单说明一下create()这个方法:
- 作用:用中序、后序序列构建子树
- 参数:构建当前子树要用到的中序序列数组以及构建当前子树能使用的范围、后序序列数组 以及 构建当前子树能使用的范围
(如图所示,构建每棵子树中后序数组使用范围不同~)
TreeNode left = create(inorder, inleft, index, postorder, poleft, poleft +(index - inleft));
TreeNode right = create(inorder, index + 1, inright, postorder, poleft +(index - inleft), poright - 1);
层序遍历二叉树
- 左视图其实就是层级遍历二叉树然后输出每一层的第一个节点值
- 右视图其实就是层级遍历二叉树然后输出每一层最后一个节点
代码
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
int[] inorder = new int[n];
int[] postorder = new int[n];
for (int i = 0; i < n; ++i) {
inorder[i] = sc.nextInt();
}
sc.nextLine();
for (int i = 0; i < n; ++i) {
postorder[i] = sc.nextInt();
}
TreeNode root = create(inorder, 0, n, postorder, 0, n);
Queue<TreeNode> que = new LinkedList<>();
List<Integer> left = new LinkedList<>();
List<Integer> right = new LinkedList<>();
que.add(root);
while (!que.isEmpty()) {
int x = que.size();
for (int i = 0; i < x; ++i) {
TreeNode node = que.poll();
if(i == 0) left.add(node.val);
if(i == x - 1)right.add(node.val);
if(node.left != null) que.add(node.left);
if(node.right != null) que.add(node.right);
}
}
for (int i : left) System.out.print(i + " ");
System.out.println();
for(int i : right) System.out.print(i + " ");
}
public static TreeNode create(int[] inorder, int inleft,int inright,int[] postorder, int poleft, int poright) {
if(poright - poleft == 0)return null;
if(poright - poleft == 1)return new TreeNode(postorder[poleft]);
TreeNode root = new TreeNode(postorder[poright - 1]);
int index = 0;
int rootVal = postorder[poright - 1];
for (int i = 0; i < inright; ++i) {
if (inorder[i] == rootVal) {
index = i;
break;
}
}
TreeNode left = create(inorder, inleft, index, postorder, poleft, poleft +(index - inleft));
TreeNode right = create(inorder, index + 1, inright, postorder, poleft +(index - inleft), poright - 1);
root.left = left;
root.right = right;
return root;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
left = null;
right = null;
}
}