0
0
DSA Goprogramming~10 mins

Count Total Nodes in Binary Tree in DSA Go - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Anull
Bnil
C0
Dempty
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'null' instead of 'nil' causes a compile error.
Returning 0 without checking for nil causes runtime errors.
2fill in blank
medium

Complete 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'
A1
B0
Croot.Val
DcountNodes(root)
Attempts:
3 left
💡 Hint
Common Mistakes
Adding 0 instead of 1 results in always zero count.
Using root.Val adds node value, not count.
3fill in blank
hard

Fix 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'
Anil
Broot.Right
Croot
Droot.Left
Attempts:
3 left
💡 Hint
Common Mistakes
Using root.Right twice counts right subtree twice.
Using root or nil causes infinite recursion or errors.
4fill in blank
hard

Fill 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'
Anil
B0
C1
Dempty
Attempts:
3 left
💡 Hint
Common Mistakes
Returning 1 when root is nil inflates count.
Checking for 'empty' instead of nil causes errors.
5fill in blank
hard

Fill 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'
Anil
B0
C1
Droot
Attempts:
3 left
💡 Hint
Common Mistakes
Returning root instead of 0 in base case.
Adding 0 instead of 1 for current node.