Leetcode 199: Binary Tree Right Side View

grid47
grid47
Exploring patterns and algorithms
Oct 18, 2024 6 min read

A glowing tree viewed from the right side, with the rightmost nodes gently illuminating.
Solution to LeetCode 199: Binary Tree Right Side View Problem

You are given the root of a binary tree. Imagine yourself standing on the right side of the tree, and return the values of the nodes you can see when viewed from the right, ordered from top to bottom.
Problem
Approach
Steps
Complexity
Input: The input is a binary tree represented by the root node. The tree is defined as a TreeNode with properties: val, left, and right.
Example: root = [3,1,4,null,2]
Constraints:
• The number of nodes in the tree is in the range [0, 100].
• -100 <= Node.val <= 100
Output: Return an array of integers representing the values of the nodes visible from the right side of the tree, ordered from top to bottom.
Example: [3,4,2]
Constraints:
• The output should be an array of integers.
Goal: The goal is to find the nodes that are visible from the right side of the binary tree.
Steps:
• Use level-order traversal (breadth-first search) of the tree.
• At each level, record the last node encountered in that level, as it is the one visible from the right.
• Return the recorded nodes in the order they are encountered from top to bottom.
Goal: The input tree will contain between 0 and 100 nodes, with each node's value between -100 and 100.
Steps:
• The tree can have a maximum of 100 nodes.
• Node values are between -100 and 100.
Assumptions:
• The binary tree is well-formed and follows the structure of a TreeNode.
Input: root = [3,1,4,null,2]
Explanation: In this example, when viewed from the right side, the visible nodes are 3 (root), 4 (right child of root), and 2 (right child of node 1). The output is [3, 4, 2].

Input: root = [1, null, 2, null, 3]
Explanation: Here, the right-side view is simply the nodes 1, 2, and 3, which are all in a straight line from top to bottom. The output is [1, 2, 3].

Input: root = []
Explanation: If the tree is empty, the right-side view is also empty, so the output is [].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus