> Uploading knowledge... _
[░░░░░░░░░░░░░░░░░░░░░░░░] 0%
blog logo
> CHICIO CODING_Pixels. Code. Unplugged.

Binary Tree Right Side View

Leetcode Problem 199: Binary Tree Right Side View

Problem Summary

Given the root of a binary tree, imagine standing on its right side and looking left. Return the list of node values visible from that vantage point, listed from top to bottom. For each level, only the rightmost node is visible.

Constraints:

  • The tree has between 0 and 100 nodes.
  • Node values are integers in the range [-100, 100].

Techniques

  • Tree
  • Depth-First Search
  • Breadth-First Search
  • Binary Tree

Solution

export class TreeNode {
    val: number
    left: TreeNode | null
    right: TreeNode | null

    constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
        this.val = (val === undefined ? 0 : val)
        this.left = (left === undefined ? null : left)
        this.right = (right === undefined ? null : right)
    }
}

function rightSideView(root: TreeNode | null): number[] {
    if (!root) {
        return []
    }

    let queue: TreeNode[] = [root]
    let results: number[] = []

    while (queue.length > 0) {
        let levelSize = queue.length

        while (levelSize > 0) {
            const currentNode = queue.shift()!

            if (levelSize === 1) {
                results.push(currentNode.val)
            }

            if (currentNode.left) {
                queue.push(currentNode.left)
            }

            if (currentNode.right) {
                queue.push(currentNode.right)
            }

            levelSize--
        }
    }

    return results
}