Overview
Given the root of a binary tree, return the values of nodes visible from the right side, ordered from top to bottom.
Constraints
- The number of nodes is in the range
[0, 100]. -100 <= Node.val <= 100
Examples
rightSideView([1, 2, 3, null, 5, null, 4]); // => [1, 3, 4] rightSideView([1, null, 3]); // => [1, 3]
Solution
Reveal solution
function rightSideView(root) {
if (!root) return [];
const result = [];
const 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;
}Resources
binary-tree-right-side-view.js
Binary Tree Right Side View
mediumcodingAlgorithmsBinary Trees
Overview
Given the root of a binary tree, return the values of nodes visible from the right side, ordered from top to bottom.
Constraints
- The number of nodes is in the range
[0, 100]. -100 <= Node.val <= 100
Examples
rightSideView([1, 2, 3, null, 5, null, 4]); // => [1, 3, 4] rightSideView([1, null, 3]); // => [1, 3]
Solution
Reveal solution
function rightSideView(root) {
if (!root) return [];
const result = [];
const 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;
}Resources
NameTopicDifficulty
103 of 103 problems