思路
二叉树的右视图也是基于二叉树的层序遍历来实现的,首先要知道二叉树的层序遍历怎么实现,参考:二叉树的层序遍历,然后右视图就是取层序遍历里面每一层最后的一个元素,可以想到,每次从右侧去看的二叉树的话,那么看到的元素一定是这一层最右侧的元素,所以我们每次循环当前层的时候判断如果是最后一个元素的时候就push到结果值中去
从下图可以看到,右视图的话会看到的结果是[5,6,2]
层序遍历的结果是[ [5] , [4,6] , [1,2] ],那么我们需要的就是层序遍历的每一层最后一个值
实现
var rightSideView = function(root) {
if(!root) return [];
let result = [], queue = [root]
while(queue.length){
let len = queue.length;
while(len--){
const node = queue.shift();
node.left && queue.push(node.left)
node.right && queue.push(node.right)
if(!len){ // 当前层最后一个元素
result.push(node.val)
}
}
}
return result;
};