Skip to main content

Binary Tree Right Side View

LeetCode 199 | Difficulty: Medium​

Medium

Problem Description​

Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

Example 1:

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

Output: [1,3,4]

Explanation:

Example 2:

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

Output: [1,3,4,5]

Explanation:

Example 3:

Input: root = [1,null,3]

Output: [1,3]

Example 4:

Input: root = []

Output: []

Constraints:

- The number of nodes in the tree is in the range `[0, 100]`.

- `-100 <= Node.val <= 100`

Topics: Tree, Depth-First Search, Breadth-First Search, Binary Tree


Approach​

Tree DFS​

Traverse the tree recursively (or with a stack). At each node, decide: what information do I need from the left/right subtrees? Process: go left β†’ go right β†’ combine results. Consider preorder, inorder, or postorder traversal based on when you need to process the node.

When to use

Path problems, subtree properties, tree structure manipulation.

Tree BFS (Level-Order)​

Use a queue to process the tree level by level. At each level, process all nodes in the queue, then add their children. Track the level size to know when one level ends and the next begins.

When to use

Level-order traversal, level-based aggregation, right/left side view.


Solutions​

Solution 1: C# (Best: 292 ms)​

MetricValue
Runtime292 ms
MemoryN/A
Date2018-07-13
Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public IList<int> RightSideView(TreeNode root) {
Queue<TreeNode> level = new Queue<TreeNode>();
List<int> result = new List<int>();
if (root == null) return result;
level.Enqueue(root);
while (level.Count != 0)
{
int rowCount = level.Count;
for (int i = 0; i < rowCount; i++)
{
var front = level.Dequeue();
if (front.left != null) level.Enqueue(front.left);
if (front.right != null) level.Enqueue(front.right);
if(i==rowCount-1) result.Add(front.val);
}
}
return result;
}
}

Complexity Analysis​

ApproachTimeSpace
Tree Traversal$O(n)$$O(h)$

Interview Tips​

Key Points
  • Discuss the brute force approach first, then optimize. Explain your thought process.
  • Consider: "What information do I need from each subtree?" β€” this defines your recursive return value.