题解 | #输出二叉树的右视图#
输出二叉树的右视图
https://www.nowcoder.com/practice/c9480213597e45f4807880c763ddd5f0
方法:
先用上一道题的建树方法建树,再用层次遍历即可:
public class Solution { public int[] solve (int[] xianxu, int[] zhongxu) { //将xianxu节点的值映射到相应的中序节点的下标。 TreeNode root=buildTree(xianxu,zhongxu,0,xianxu.length-1,0,zhongxu.length-1); Queue<TreeNode>queue=new LinkedList<>(); queue.offer(root); List<Integer>list=new ArrayList<>(); while(!queue.isEmpty()){ int size=queue.size(); TreeNode cur=null; for(int i=0;i<size;i++){ cur=queue.poll(); if(cur.left!=null)queue.offer(cur.left); if(cur.right!=null)queue.offer(cur.right); } list.add(cur.val); } int []r=new int[list.size()]; for(int i=0;i<list.size();i++) r[i]=list.get(i); return r; } public TreeNode buildTree(int[]p,int[]v,int pl,int ph,int vl,int vh){ if(pl>ph) return null; int vm=vl; for(;vm<=vh;vm++) if(v[vm]==p[pl]) break; TreeNode node=new TreeNode(v[vm]); node.left=buildTree(p,v,pl+1,pl+vm-vl,vl,vm-1); node.right=buildTree(p,v,pl+vm-vl+1,ph,vm+1,vh); return node; } }