import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 求二叉树的右视图 * @param preOrder int整型一维数组 先序遍历 * @param inOrder int整型一维数组 中序遍历 * @return int整型一维数组 */ public int[] solve (int[] preOrder, int[] inOrder) { // write code here TreeNode root = buildTree(preOrder, inOrder); List<Integer> ans = new LinkedList<>(); Queue<TreeNode> que = new LinkedList<>(); if(root != null)que.offer(root); while(!que.isEmpty()){ int size = que.size(); while(size > 0){ TreeNode cur = que.poll(); size--; if(cur.left != null)que.offer(cur.left); if(cur.right != null)que.offer(cur.right); // 每层最后一个元素即是最右边节点 if(size == 0){ ans.add(cur.val); } } } return ans.stream().mapToInt(Integer::intValue).toArray(); } /** 递归构建二叉树 */ private TreeNode buildTree(int[] preOrder, int[] inOrder){ if(preOrder.length == 0 || inOrder.length == 0)return null; TreeNode root = new TreeNode(preOrder[0]); for(int i = 0; i < inOrder.length; i++){ if(inOrder[i] == preOrder[0]){ int[] preLeft = new int[i]; System.arraycopy(preOrder, 1, preLeft, 0, i); int[] preRight = new int[preOrder.length-i-1]; System.arraycopy(preOrder, i+1, preRight, 0, preRight.length); int[] inLeft = new int[i]; System.arraycopy(inOrder, 0, inLeft, 0, i); int[] inRight = new int[preRight.length]; System.arraycopy(inOrder, i+1, inRight, 0, preRight.length); root.left = buildTree(preLeft, inLeft); root.right = buildTree(preRight, inRight); break; } } return root; } }
递归构建二叉树+层序遍历