题目地址:链接
思路: 每层最后一个(层序遍历)最后一个压入数组
/**
* 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 ans = [];
let q = [root];
let ceng = [];
let last = true;
while(q.length) {
let node = q.shift();
if(!node) continue;
if(node.left) ceng.push(node.left);
if(node.right)ceng.push(node.right);
if(q.length == 0) {
ans.push(node.val);
q = [...ceng];
ceng = [];
last = true;
}
}
return ans;
};
8万+

被折叠的 条评论
为什么被折叠?



