↓Skip to main content
  1. LeetCode/

LeetCode 199: Binary Tree Right Side View

·1 min· ·
LeetCode Medium Tree Depth-First-Search Breadth-First-Search Binary-Tree
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-29

  • Submissions: Time Limit Exceeded → Accepted → Runtime Error → Accepted ×2

Approach
#

From the right you see only the rightmost node of each level (Tree Template 2). Walk levels with BFS and record each level’s last node.

My Attempts
#

Attempt 1’s loop never moved to the next level, looping forever on a single node [6] (TLE); another missed the empty tree.

Solution
#

class Solution:
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        res, level = [], [root] if root else []
        while level:
            res.append(level[-1].val)
            level = [c for n in level for c in (n.left, n.right) if c]
        return res

Complexity
#

Time O(n), space O(w).

Mistakes to Avoid
#

  • The rightmost node is not always a right child: when the right subtree is shorter, deeper left-subtree nodes show.

Interview Explanation
#

The right view is each level’s rightmost node, so I BFS level by level and record the last one. Time O(n).

Related

LeetCode 1448: Count Good Nodes in Binary Tree
·1 min
LeetCode Medium Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 1448 note: pass the path maximum down during DFS; a node is good when its value is at least that maximum
LeetCode 102: Binary Tree Level Order Traversal
·1 min
LeetCode Medium Tree Breadth-First-Search Binary-Tree
LeetCode 102 note: BFS one whole level at a time, building the next level from the current one; an empty tree returns an empty list
LeetCode 230: Kth Smallest Element in a BST
·1 min
LeetCode Medium Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 230 note: a BST’s in-order traversal is ascending, so stop an iterative in-order walk at the k-th node
LeetCode 98: Validate Binary Search Tree
·2 mins
LeetCode Medium Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 98 note: every node has a valid range (low, high); going left the upper bound becomes the node and going right the lower bound does; comparing parent and child is not enough
LeetCode 965: Univalued Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 965 note: every value must equal the root’s; compare values while recursing, not the booleans the recursion returns
LeetCode 993: Cousins in Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 993 note: cousins share a depth but not a parent; record x’s and y’s depth and parent during DFS and compare