算法 二叉树的右视图
题目
给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
链接:https://leetcode.cn/problems/binary-tree-right-side-view/
思路:
- 这一题,可以简单理解成——遍历单行的节点,左节点先进队列,然后右节点再进入
- 判断该节点是否为最后一个节点,是则放入res数组中
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var rightSideView = function(root) {
const res = []
const queue = [root]
while(queue.length && root !== null){
let length = queue.length
while(length--){
const node = queue.shift()
if(!length){
res.push(node.val)
}
node.left && queue.push(node.left)
node.right && queue.push(node.right)
}
}
return res
};