牛客BM41 输出二叉树的右视图
题目:给出树的前序、中序序列,输出树的右视图
思路:层序遍历
- 这道题刚开始看很懵,什么右视图??看了评论区,其实右视图就是每一层的最后一个结点的集合
- 所以,层序遍历,到了当前层的最后一个结点就记录下就行了
- 但题目没有给完整的树,而是遍历序列,所以其实是BM40 + 层序遍历
代码:
public int[] solve (int[] xianxu, int[] zhongxu) {//输出右视图
TreeNode root = BuildTree(xianxu, zhongxu);
List<Integer> res = new ArrayList<Integer>();//收集结果
//特殊
if(root.left == null && root.right == null) {
res.add(root.val);
return res.stream().mapToInt(Integer::valueOf).toArray();
}
//层序遍历
Queue<TreeNode> que = new LinkedBlockingQueue<TreeNode>();
que.offer(root);
while(!que.isEmpty()) {
int size = que.size();
for(int i = 0; i < size; i++) {
TreeNode cur = que.poll();
if(cur.left != null) que.add(cur.left);
if(cur.right != null) que.add(cur.right);
if(i == size - 1) {
res.add(cur.val);
}
}//for
}//while
return res.stream().mapToInt(Integer::valueOf).toArray();
}//fun
public static TreeNode BuildTree(int[] pre, int[] vin) {//重建二叉树
if(pre.length == 0 || vin.length == 0) return null;
if(pre.length == 1 && vin.length == 1 && pre[0] == vin[0]) return new TreeNode(pre[0]);
TreeNode root = new TreeNode(pre[0]);
int n = pre.length;
//在中序序列中找根
for(int i = 0; i < n; i++) {
if(vin[i] == pre[0]) {
root.left = BuildTree(Arrays.copyOfRange(pre, 1, i+1), Arrays.copyOfRange(vin, 0, i));
root.right = BuildTree(Arrays.copyOfRange(pre, i+1, n), Arrays.copyOfRange(vin, i+1, n));
break;
}
}
return root;
}//build