给定一个二叉树的 根节点 root
,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例 1:
输入: [1,2,3,null,5,null,4] 输出: [1,3,4]
示例 2:
输入: [1,null,3] 输出: [1,3]
示例 3:
输入: [] 输出: []
提示:
- 二叉树的节点个数的范围是
[0,100]
-100 <= Node.val <= 100
思路:
1.该算法是可以为层次遍历;
2. 将根节点赋值给quen,quen中最后一个元素是二叉树右视图的值;
3.while循环控制层数,其中的for循环保证取到的值为二叉树右视图的值
/**
* 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) {
if(!root) return []
let quen=[root]
let arr=[]
while(quen.length){
let len=quen.length
arr.push(quen[len-1].val)
for(let i=0;i<len;i++){
let node=quen.shift()
node.left&&quen.push(node.left)
node.right&&quen.push(node.right)
}
}
return arr
};