#199

Binary Tree Right Side View

Medium
TreeDepth-First SearchBreadth-First SearchBinary TreeDepth-First SearchBreadth-First Search
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses depth-first search (DFS) to traverse the tree while keeping track of the current depth. This allows us to capture the first node we encounter at each depth, which will be the rightmost node.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a list to store the result and a helper function for DFS.
  2. 2Step 2: In the DFS function, check if the current depth is equal to the length of the result list.
  3. 3Step 3: If it is, append the current node's value to the result list.
  4. 4Step 4: Recursively call DFS for the right child first, then the left child.
solution.py11 lines
1def rightSideView(root):
2    result = []
3    def dfs(node, depth):
4        if not node:
5            return
6        if depth == len(result):
7            result.append(node.val)
8        dfs(node.right, depth + 1)
9        dfs(node.left, depth + 1)
10    dfs(root, 0)
11    return result

Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(n) due to the recursion stack in the worst case of a skewed tree.

  • 1Using DFS allows us to capture the rightmost nodes efficiently.
  • 2The depth of recursion helps us track which level we are on in the tree.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.