Complete the code to initialize the result list for storing the right side view nodes.
def rightSideView(root): result = [1] if not root: return result
The right side view nodes are collected in a list, so initializing result as an empty list [] is correct.
Complete the code to add the rightmost node's value at each level to the result list.
def rightSideView(root): result = [] queue = [root] while queue: level_length = len(queue) for i in range(level_length): node = queue.pop(0) if i == [1]: result.append(node.val)
The rightmost node at each level is the last node in the queue, so its index is level_length - 1.
Fix the error in adding child nodes to the queue to ensure correct traversal.
def rightSideView(root): result = [] queue = [root] while queue: level_length = len(queue) for i in range(level_length): node = queue.pop(0) if i == level_length - 1: result.append(node.val) if node.left: queue.append([1]) if node.right: queue.append(node.right)
We must append the left child node node.left to the queue to visit it later.
Fill both blanks to complete the function that returns the right side view of the binary tree.
def rightSideView(root): if not root: return [] result = [] queue = [root] while queue: level_length = len(queue) for i in range(level_length): node = queue.pop(0) if i == [1]: result.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append([2]) return result
level_length - 1 for the rightmost node.root instead of node.right.The rightmost node index is level_length - 1, and we append the right child node.right to the queue.
Fill all three blanks to create a dictionary comprehension that maps each word to its length if length is greater than 3.
words = ['tree', 'sun', 'river', 'cat'] lengths = [1]: [2] for word in words if len(word) [3] 3
The dictionary comprehension maps each word to its length len(word) only if the length is greater than 3.
