199.二叉树的右视图

二叉树的右视图

给定一个二叉树的根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var rightSideView = function (root) {
if (!root) return [];
const result = [], queue = [root];
while (queue.length) {
const size = queue.length;
for (let i = 0; i < size; i++) {
const node = queue.shift();
if (i === size - 1) result.push(node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}
return result;
};

199.二叉树的右视图
https://leetcode.lz5z.com/199.binary-tree-right-side-view/
作者
tickli
发布于
2024年6月4日
许可协议