0
0
DSA C++programming~10 mins

Count Total Nodes in Binary Tree in DSA C++ - Interactive Practice

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

Complete the code to return the total number of nodes in the binary tree.

DSA C++
int countNodes(Node* root) {
    if (root == nullptr) {
        return 0;
    }
    return 1 + countNodes(root->[1]) + countNodes(root->right);
}
Drag options to blanks, or click blank then click option'
Aright
Bleft
Cparent
Dchild
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'right' instead of 'left' for the left subtree.
Trying to access a non-existent 'parent' pointer.
2fill in blank
medium

Complete the code to correctly check if the tree is empty.

DSA C++
int countNodes(Node* root) {
    if ([1] == nullptr) {
        return 0;
    }
    return 1 + countNodes(root->left) + countNodes(root->right);
}
Drag options to blanks, or click blank then click option'
Aroot->left
Broot->right
Croot
Dnullptr
Attempts:
3 left
💡 Hint
Common Mistakes
Checking left or right child instead of root.
Comparing to a variable instead of nullptr.
3fill in blank
hard

Fix the error in the recursive call to count nodes in the right subtree.

DSA C++
int countNodes(Node* root) {
    if (root == nullptr) {
        return 0;
    }
    return 1 + countNodes(root->left) + countNodes(root->[1]);
}
Drag options to blanks, or click blank then click option'
Aright
Bparent
Cchild
Dnext
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'parent' or 'next' which do not exist in the node structure.
Using 'child' which is not a pointer name.
4fill in blank
hard

Fill both blanks to complete the function that counts nodes using recursion.

DSA C++
int countNodes(Node* root) {
    if (root == [1]) {
        return 0;
    }
    return 1 + countNodes(root->[2]) + countNodes(root->right);
}
Drag options to blanks, or click blank then click option'
Anullptr
Broot
Cleft
Dright
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'root' instead of 'nullptr' in base case.
Using 'right' instead of 'left' for left subtree.
5fill in blank
hard

Fill all three blanks to complete the recursive node counting function correctly.

DSA C++
int countNodes(Node* root) {
    if (root == [1]) {
        return 0;
    }
    return 1 + countNodes(root->[2]) + countNodes(root->[3]);
}
Drag options to blanks, or click blank then click option'
Anullptr
Bleft
Cright
Dparent
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'parent' which does not exist in node structure.
Mixing up left and right pointers.