Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new node in the binary tree.
DSA Python
class Node: def __init__(self, data): self.data = data self.left = None self.right = None root = Node([1])
Attempts:
3 left
💡 Hint
Common Mistakes
Using None instead of a value for the root node.
Using a variable name instead of a value.
✗ Incorrect
The root node should be initialized with the value 10 to create the binary tree's root.
2fill in blank
mediumComplete the code to insert a node to the left of the root.
DSA Python
root.left = Node([1])Attempts:
3 left
💡 Hint
Common Mistakes
Assigning None instead of a node.
Assigning the root node itself.
✗ Incorrect
The left child of the root is assigned a new node with value 5.
3fill in blank
hardFix the error in the function to print the top view of the binary tree.
DSA Python
def top_view(root): if root is None: return queue = [(root, 0)] top_nodes = {} while queue: node, hd = queue.pop(0) if hd not in top_nodes: top_nodes[[1]] = node.data if node.left: queue.append((node.left, hd - 1)) if node.right: queue.append((node.right, hd + 1)) for key in sorted(top_nodes): print(top_nodes[key], end=' ')
Attempts:
3 left
💡 Hint
Common Mistakes
Using the node object as a key instead of horizontal distance.
Using the queue or root as a key.
✗ Incorrect
The horizontal distance (hd) is used as the key to store the first node at that distance.
4fill in blank
hardFill both blanks to complete the code that builds the top view dictionary.
DSA Python
def top_view(root): if root is None: return queue = [(root, 0)] top_nodes = {} while queue: node, hd = queue.pop(0) if [1] not in top_nodes: top_nodes[[2]] = node.data if node.left: queue.append((node.left, hd - 1)) if node.right: queue.append((node.right, hd + 1))
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variables for the key in the dictionary.
Using node or queue as keys.
✗ Incorrect
Both blanks should be the horizontal distance 'hd' to correctly track nodes by their horizontal distance.
5fill in blank
hardFill all three blanks to complete the code that prints the top view nodes in order.
DSA Python
def top_view(root): if root is None: return queue = [(root, 0)] top_nodes = {} while queue: node, hd = queue.pop(0) if hd not in top_nodes: top_nodes[hd] = node.data if node.left: queue.append((node.left, hd - 1)) if node.right: queue.append((node.right, hd + 1)) for key in [1](top_nodes): print(top_nodes[[2]], end=[3])
Attempts:
3 left
💡 Hint
Common Mistakes
Not sorting the keys before printing.
Using wrong variable names to access dictionary.
Printing without spaces.
✗ Incorrect
We sort the keys to print nodes from left to right, use 'key' to access values, and print with a space separator.
