解题思路:先将原树给复原,然后层序遍历二叉树,将每层的最后一个保存集合里,然后再转数组返回。时间复杂度O(N),空间复杂度O(N)。
import java.util.*;
import java.util.stream.Collectors;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 求二叉树的右视图
* @param xianxu int整型一维数组 先序遍历
* @param zhongxu int整型一维数组 中序遍历
* @return int整型一维数组
*/
public int[] solve (int[] xianxu, int[] zhongxu) {
// write code here
if (xianxu.length == 0 || zhongxu.length == 0) {
return null;
}
//1、重建二叉树
List<Integer> list1 = Arrays.stream(xianxu).boxed().collect(
Collectors.toList());
List<Integer> list2 = Arrays.stream(zhongxu).boxed().collect(
Collectors.toList());
TreeNode root = step1(list1, list2);
//2、层序遍历取最后一个
Queue<TreeNode> queue = new LinkedList<>();
List<Integer> list = new ArrayList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (i == size - 1) {
list.add(node.val);
}
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
}
//3、转数组并返回
return list.stream().mapToInt(Integer::valueOf).toArray();
}
//重新构建二叉树
private TreeNode step1(List<Integer> list1, List<Integer> list2) {
if (list1.size() == 0) {
return null;
}
TreeNode root = new TreeNode(list1.get(0));
int index = list2.indexOf(list1.get(0));
root.left = step1(list1.subList(1, index + 1), list2.subList(0, index));
root.right = step1(list1.subList(index + 1, list1.size()),
list2.subList(index + 1, list2.size()));
return root;
}
}