Complete the code to return the total number of nodes in the binary tree.
int countNodes(Node* root) {
if (root == nullptr) {
return 0;
}
return 1 + countNodes(root->[1]) + countNodes(root->right);
}The function counts nodes by adding 1 for the current node plus the counts of nodes in the left and right subtrees. The left subtree is accessed by root->left.
Complete the code to correctly check if the tree is empty.
int countNodes(Node* root) {
if ([1] == nullptr) {
return 0;
}
return 1 + countNodes(root->left) + countNodes(root->right);
}nullptr.To check if the tree is empty, we check if the root pointer itself is nullptr.
Fix the error in the recursive call to count nodes in the right subtree.
int countNodes(Node* root) {
if (root == nullptr) {
return 0;
}
return 1 + countNodes(root->left) + countNodes(root->[1]);
}The right subtree is accessed by root->right. Using any other pointer name will cause an error or wrong result.
Fill both blanks to complete the function that counts nodes using recursion.
int countNodes(Node* root) {
if (root == [1]) {
return 0;
}
return 1 + countNodes(root->[2]) + countNodes(root->right);
}The base case checks if root == nullptr to stop recursion. The left subtree is accessed by root->left.
Fill all three blanks to complete the recursive node counting function correctly.
int countNodes(Node* root) {
if (root == [1]) {
return 0;
}
return 1 + countNodes(root->[2]) + countNodes(root->[3]);
}The base case checks if root == nullptr. The left and right subtrees are accessed by root->left and root->right respectively.