Binary Tree Right Side View Medium 0 attempts
LeetCode ↗

Binary Tree Right Side View

Medium TreeBinary TreeDFS LeetCode

Given a binary tree, return the values of the nodes you can see ordered from top to bottom when looking at the tree from the right side.

Example: root = [1,2,3,null,5,null,4] → Output: [1,3,4]

Sample Input
Sample Output
Constraints
  • 0 <= number of nodes <= 100
  • -100 <= Node.val <= 100

BFS Level Order (Last of Each Level)

function rightSideView(root) {
  if (!root) return [];
  const result = [], q = [root];
  while (q.length) {
    const size = q.length;
    for (let i = 0; i < size; i++) {
      const node = q.shift();
      if (i === size - 1) result.push(node.val);
      if (node.left) q.push(node.left);
      if (node.right) q.push(node.right);
    }
  }
  return result;
}

Time: O(n) | Space: O(n)

Saved in this browser only. Private to you.

JavaScript