A-054● Day 542026.06.30mediumleetcode #199neetcode150
Binary Tree Right Side View
#tree#depth-first-search#breadth-first-search#binary-tree
01
Problem
· problemGiven 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.
constraints
- · The number of nodes in the tree is in the range [0, 100]
- · -100 ≤ Node.val ≤ 100
// paraphrased summary — see source for full text
examples
02
Pre-solve
· pre-solve● 1list shown→● 2select→● 3reveal
- ☐Does right side view mean nodes without a right child?
- ☐Should we use BFS or DFS for this problem?
- ☐What should we return for an empty tree?
- ☐Can we only traverse the right subtree of each node?
- ☐Why do we need to know the current level size?
- ☐How do we identify the rightmost node at each level?
- ☐Do we add null nodes to the queue?
check the items you would ask, then press confirm
// session-only state — refresh resets (repeatable practice)
03
Logic Structure
· logic● 1slots shown→● 2pick per slot→● 3reveal
// pick one code line per slot to assemble the algorithm flow. no typing — just the logic skeleton.
step 1· Initialize result list
○
res = []
○
res = None
○
res = {}step 2· Initialize queue with root
○
q = collections.deque([root])
○
q = [root]
○
q = collections.deque()
step 3· While loop for each level
○
while q:
○
if q:
○
while len(q) > 1:
step 4· Setup current level│ nested
○
qLen = len(q)
○
qLen = q.maxlen; rightSide = 0
○
qLen = len(q) - 1
step 5· Iterate through current level│ nested
○
for i in range(qLen):
○
for node in q:
○
for i in range(qLen + 1):
step 6· Dequeue and track rightmost│ │ nested
○
node = q.popleft()
○
rightSide = node q.append(node.left) q.append(node.right)
○
if node:
rightSide = nodestep 7· Append rightmost value│ nested
○
if rightSide:
○
res.append(rightSide)
○
res.append(rightSide) if rightSide else pass
pick one option per slot
// format: slot — recursive / DP patterns use ordering / state-first formats. ADR-08 follow-up.
04
Solve · Trace
· solvemental dry-run cases
// walk each case in your head; expand the worked example below if stuck.
case 1
[1,2,3,null,5,null,4]→
[1,3,4]
case 2
[1,2,3,4,null,null,null,5]→
[1,3,4,5]
case 3
[1,null,3]→
[1,3]
case 4
[]→
[]
// UI does not walk-through — you do the dry-run mentally. Expand the worked example if stuck.