Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the height of the binary tree node.
DSA Python
def height(node): if node is None: return 0 left_height = height(node.left) right_height = height(node.right) return 1 + max(left_height, [1])
Attempts:
3 left
š” Hint
Common Mistakes
Returning min instead of max.
Using node.value instead of child's height.
ā Incorrect
The height of a node is 1 plus the maximum height of its left and right children. So we use max(left_height, right_height).
2fill in blank
mediumComplete the code to check if the current node is balanced by comparing heights of left and right subtrees.
DSA Python
def is_balanced(node): if node is None: return True left_height = height(node.left) right_height = height(node.right) if abs(left_height - right_height) > [1]: return False return is_balanced(node.left) and is_balanced(node.right)
Attempts:
3 left
š” Hint
Common Mistakes
Using 0 instead of 1, which is too strict.
Using 2 or more, which allows unbalanced trees.
ā Incorrect
A binary tree is balanced if the height difference between left and right subtrees is at most 1.
3fill in blank
hardFix the error in the code to correctly check if the tree is balanced by returning a boolean.
DSA Python
def check_balanced(node): if node is None: return True left = check_balanced(node.left) right = check_balanced(node.right) if left is False or right is False: return False if abs(height(node.left) - height(node.right)) > [1]: return False return True
Attempts:
3 left
š” Hint
Common Mistakes
Using 0 which is too strict.
Returning None instead of False.
ā Incorrect
The height difference must not exceed 1 for the tree to be balanced.
4fill in blank
hardFill both blanks to create a dictionary comprehension that maps each node's value to its height if the height is greater than 1.
DSA Python
def node_heights_dict(nodes): return {node.value: [1] for node in nodes if [2]
Attempts:
3 left
š” Hint
Common Mistakes
Using node.value as value instead of height.
Filtering by node.value instead of height.
ā Incorrect
We map node.value to height(node) only if height(node) > 1.
5fill in blank
hardFill all three blanks to create a dictionary comprehension that maps uppercase node values to their heights if height is less than or equal to 2.
DSA Python
def filtered_node_heights(nodes): return [1]: [2] for node in nodes if [3]
Attempts:
3 left
š” Hint
Common Mistakes
Using node.value instead of uppercase.
Filtering by node.value instead of height.
ā Incorrect
Keys are uppercase node values, values are heights, filtered by height <= 2.
