根据40题和26题

只需重现二叉树,然后层序遍历一下,将每一个level的最后一个元素输出即为右视图

function solve( xianxu ,  zhongxu ) {
  function ListNode(val){
    this.left = null;
    this.right = null;
    this.val = val;
  }
  function getTree(pre,vin){
    if(pre.length==0 || vin.length==0)
      return null;
    
    let root = new ListNode(pre[0]);
    let rootIndexInVin = vin.indexOf(pre[0]);
    
    root.left  = getTree( pre.slice(1,rootIndexInVin+1),          vin.slice(0,rootIndexInVin))
    root.right = getTree( pre.slice(rootIndexInVin+1,pre.length), vin.slice(rootIndexInVin+1,vin.length));
    
    return root;
  }
  function levelOrder(root,level){
    if(root==null)
      return;
    if(level>=levelAns.length)
      levelAns.push([]);
    
    levelAns[level].push(root.val);
    
    levelOrder(root.left,level+1)
    levelOrder(root.right,level+1);
  }
  let tree = getTree(xianxu,zhongxu);
  let levelAns = [];
  levelOrder(tree,0);
  let ans = [];
  levelAns.forEach(item=>{
    ans.push(item[item.length-1]);
  })
  return ans;
}
module.exports = {
    solve : solve
};



优化一下:层序遍历的过程中即可得到结果,不需要层序遍历之后再循环得到结果


function solve( xianxu ,  zhongxu ) {
  
  function levelOrder(root){
    if(root==null)
      return;
    let queue = [];//辅助队列
    let res = [];//结果数组
    queue.push(root);
    while(queue.length){
      const len = queue.length;
      for(let i=0; i<len; i++){
        const node = queue.shift();
        if(i==len-1)  res.push(node.val);//说明是本行的最后一个了
        if(node.left)  queue.push(node.left);
        if(node.right)  queue.push(node.right);
      }
    }
    return res;
  }
  let tree = getTree(xianxu,zhongxu);
  return levelOrder(tree);
}
module.exports = {
    solve : solve
};