//分两步,第一步重建二叉树,第二步,层序遍历二叉树,取每一层最右边的节点即为右视图
public int[] solve (int[] xianxu, int[] zhongxu) { // write code here TreeNode root = reBuild(xianxu,0,xianxu.length-1,zhongxu,0, zhongxu.length-1); int[] res = cenxu(root); return res; } private int[] cenxu(TreeNode root){ Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); List<Integer> res = new ArrayList<>(); while(queue.size()>0){ int len = queue.size(); for(int i=1;i<=len;i++){ TreeNode tn = queue.poll(); if(tn.left!=null) queue.add(tn.left); if(tn.right!=null) queue.add(tn.right); if(i==len) res.add(tn.val); } } int[] r = new int[res.size()]; int y = 0; for(int a:res){ r[y++] = a; } return r; } private TreeNode reBuild(int[] xianxu,int xbegin,int xend,int[] zhongxu, int zbegin,int zend){ if(xbegin>xend || zbegin > zend) return null; if(xbegin==xend) return new TreeNode(xianxu[xbegin]); int temp = xianxu[xbegin]; int index = 0; for(int i=zbegin;i<=zend;i++){ if(zhongxu[i]==temp){ index = i; break; } } //zhongxu zbegin - index-1 index+1 - zend //xianxu xbegin+1 - xbegin+index-zbegin xbegin+index-zbegin+1-- xend TreeNode left = reBuild(xianxu,xbegin+1,xbegin+index-zbegin,zhongxu,zbegin,index-1); TreeNode right = reBuild(xianxu,xbegin+index-zbegin+1,xend,zhongxu,index+1,zend); TreeNode root = new TreeNode(temp); root.left = left; root.right = right; return root; }