Binary Tree Right Side View Medium 0 attempts
LeetCode ↗

Binary Tree Right Side View

Medium TreeBinary TreeDFS LeetCode

You're given the root of a binary tree. Imagine standing to its right and looking at the tree edge-on: return the value of the rightmost node visible at each level, ordered from the top level down.

Input Format
Implement rightSideView(root). Inputs below show JavaScript function arguments; there is no stdin parsing. Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.
Output Format
Return the result described in the statement.

Sample Input and Output

Example 1 ยท Run Sample

Input
root = [1,2,3,null,5,null,4]
Output
[1,3,4]

Example 2

Input
root = []
Output
[]
Constraints
  • 0 <= number of nodes <= 100
  • -100 <= Node.val <= 100
Test Cases (2)
Case 1
Args: [[1,2,3,null,5,null,4]] Expected: [1,3,4]
Case 2
Args: [[]] Expected: []

BFS Level Order (Last of Each Level)

javascript
function rightSideView(root) {
  if (!root) return [];
  const result = [], q = [root];
  let head = 0;
  while (head < q.length) {
    const size = q.length - head;
    for (let i = 0; i < size; i++) {
      const node = q[head++];
      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