Grokking the Coding Interview: Patterns for Coding Questions
Vote

0% completed

​

Solution: Problem Challenge 2: Right View of a Binary Tree

.....

.....

.....

Like the course? Get enrolled and start learning!
A

Anonymous

· 2 years ago

After the for loop iterates through the length of the level, just add the node that you get after popleft. Extra logic, does not make much sense.

from collections import deque #class TreeNode: # def __init__(self, val): # self.val = val # self.left, self.right = None, None class Solution: def traverse(self, root): result = [] # List[int] if root is None: return result # TODO: Write your code here q = deque() q.append(root) while q: level_size = len(q) for _ in range(level_size): node = q.popleft() if node.left: q.append(node.left) if node.right: q.append(node.right) result.append(node.val) return result

Reading Progress

0%


Vote for new content