Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return 0 when the node is empty (nil).
DSA Go
func countNodes(root *TreeNode) int {
if root == [1] {
return 0
}
return 1 + countNodes(root.Left) + countNodes(root.Right)
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'null' instead of 'nil' causes a compile error.
Returning 0 without checking for nil causes runtime errors.
✗ Incorrect
In Go, the empty pointer is represented by nil. So we check if root == nil to handle the base case.
2fill in blank
mediumComplete the code to count nodes by adding 1 for the current node plus counts of left and right subtrees.
DSA Go
func countNodes(root *TreeNode) int {
if root == nil {
return 0
}
return [1] + countNodes(root.Left) + countNodes(root.Right)
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Adding 0 instead of 1 results in always zero count.
Using root.Val adds node value, not count.
✗ Incorrect
We add 1 for the current node, then recursively count left and right subtrees.
3fill in blank
hardFix the error in the recursive call to count left subtree nodes.
DSA Go
func countNodes(root *TreeNode) int {
if root == nil {
return 0
}
return 1 + countNodes([1]) + countNodes(root.Right)
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using root.Right twice counts right subtree twice.
Using root or nil causes infinite recursion or errors.
✗ Incorrect
To count left subtree nodes, we must call countNodes on root.Left.
4fill in blank
hardFill both blanks to complete the function that counts nodes in a binary tree.
DSA Go
func countNodes(root *TreeNode) int {
if root == [1] {
return [2]
}
return 1 + countNodes(root.Left) + countNodes(root.Right)
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning 1 when root is nil inflates count.
Checking for 'empty' instead of nil causes errors.
✗ Incorrect
When root is nil, return 0 because there are no nodes to count.
5fill in blank
hardFill all three blanks to complete the recursive count function with base case and recursive calls.
DSA Go
func countNodes(root *TreeNode) int {
if root == [1] {
return [2]
}
return [3] + countNodes(root.Left) + countNodes(root.Right)
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning root instead of 0 in base case.
Adding 0 instead of 1 for current node.
✗ Incorrect
Base case returns 0 if node is nil; otherwise add 1 for current node plus counts of left and right.