题解 | #输出二叉树的右视图#
输出二叉树的右视图
https://www.nowcoder.com/practice/c9480213597e45f4807880c763ddd5f0
就是一个还原二叉树+输出右视图,右视图我使用的是层序遍历取每层最后一个,有点复杂,时间空间还是比不上大佬们
代码如下
function solve( xianxu , zhongxu ) { // write code here function reConstructBinaryTree(pre, vin) { if(!pre.length || !vin.length) return null; let root = pre[0]; let tnode = new TreeNode(root); let index = vin.indexOf(root); tnode.left = reConstructBinaryTree(pre.slice(1,index+1), vin.slice(0,index)); tnode.right = reConstructBinaryTree(pre.slice(index+1), vin.slice(index+1)); return tnode; } let res = reConstructBinaryTree(xianxu, zhongxu); let queue = [res]; let arr = []; while(queue.length){ let len = queue.length; while(len){ let node = queue.shift(); if(node.left) queue.push(node.left); if(node.right) queue.push(node.right); if(len == 1){ arr.push(node.val); } len--; } } return arr; } module.exports = { solve : solve };