Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the height of the binary tree.
DSA Python
def height(root): if root is None: return 0 left_height = height(root.left) right_height = height(root.right) return 1 + max(left_height, [1])
Attempts:
3 left
💡 Hint
Common Mistakes
Using min instead of max
Returning left_height only
Returning right_height only
✗ Incorrect
The height of a binary tree is 1 plus the maximum height of its left and right subtrees. So we take max(left_height, right_height).
2fill in blank
mediumComplete the code to check if the tree is empty and return height 0.
DSA Python
def height(root): if [1]: return 0 # rest of the code
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' instead of 'is' for None check
Checking left or right child instead of root
✗ Incorrect
To check if the tree is empty, we check if root is None using 'is' keyword for identity comparison.
3fill in blank
hardFix the error in the recursive call to compute height of right subtree.
DSA Python
def height(root): if root is None: return 0 left_height = height(root.left) right_height = height([1]) return 1 + max(left_height, right_height)
Attempts:
3 left
💡 Hint
Common Mistakes
Passing root.left instead of root.right
Passing root instead of child nodes
✗ Incorrect
To get the height of the right subtree, we must call height on root.right.
4fill in blank
hardFill both blanks to compute height using recursion and return the correct value.
DSA Python
def height(root): if [1]: return 0 left_height = height(root.left) right_height = height(root.right) return 1 + [2](left_height, right_height)
Attempts:
3 left
💡 Hint
Common Mistakes
Using min instead of max
Using '==' instead of 'is' for None check
✗ Incorrect
Check if root is None to handle empty tree, then return 1 plus max of left and right subtree heights.
5fill in blank
hardFill all three blanks to create a dictionary of node values and their heights for nodes with height > 1.
DSA Python
def height_dict(root): if root is None: return {} left = height_dict(root.left) right = height_dict(root.right) current_height = 1 + max([1], [2]) result = {**left, **right} if current_height [3] 1: result[root.val] = current_height return result
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' or '<=' instead of '>'
Mixing up left and right subtree heights
✗ Incorrect
Calculate current height using height of left and right subtrees, then add node if height > 1.
