题解 | #输出二叉树的右视图#
输出二叉树的右视图
https://www.nowcoder.com/practice/c9480213597e45f4807880c763ddd5f0
import java.util.*; public class Solution { public int[] solve (int[] preOrder, int[] inOrder) { //层次遍历输出最右边元素 if(preOrder.length <= 1) return preOrder; Queue<TreeNode> queue = new LinkedList<>(); List<Integer> list = new LinkedList<>(); queue.add(creat(preOrder, 0, preOrder.length - 1, inOrder, 0, inOrder.length - 1)); 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.add(node.left); if(node.right != null) queue.add(node.right); } } int[] result = new int[list.size()]; for(int i = 0; i < result.length; i++){ result[i] = list.get(i); } return result; } TreeNode creat(int[] pre, int leftPre, int rightPre, int[] in, int leftIn, int rightIn){ if(leftPre > rightPre || leftIn > rightIn) return null; TreeNode root = new TreeNode(pre[leftPre]); for(int i = leftIn; i <= rightIn; i ++){ if(in[i] == pre[leftPre]){ root.left = creat(pre, leftPre + 1, leftPre + i - leftIn, in, leftIn, i - 1); root.right = creat(pre, i - leftIn + leftPre + 1, rightPre, in, i + 1, rightIn); break; } } return root; } }