I was trying to solve GeeksForGeeks problem Size of Binary Tree:
Given a binary tree of size N, you have to count number of nodes in it. For example, count of nodes in below tree is 4.
1 / \ 10 39 / 5
Unfortunately for the test case below I'm getting "incorrect answer" on my recursive code. Can someone tell me where I'm going wrong?
Input:
2 // Number of test cases
1 2 3 // Test Case #1
10 5 9 N 1 3 6 // Test Case #2
My Output:
3
9
Expected Output:
3
6
My Code:
/* Tree node structure used in the program
struct Node
{
int data;
Node* left;
Node* right;
}; */
/* Computes the number of nodes in a tree. */
int nodes=0;
void dfs(Node* node) {
if (node==NULL) return;
++nodes;
// cout << node->data << " ";
dfs(node->left);
dfs(node->right);
}
int getSize(Node* node)
{
// Your code here
dfs(node);
return nodes;
}
The mistake is that your code has a global
int nodesthat is only initialised once. WhengetSizeis called multiple times, then only at the first call you can be sure it really is zero. All other calls will just keep incrementing that counter without it having been reset.So either reset that counter just before the call to
dfsis made, or -- better -- redesign your code so that you don't need a global counter at all, for example by havingdfsreturn a counter. And if you do that, you can even makegetSizerecursive itself, without any need of a separatedfsfunction.NB: don't use
NULLin C++, butnullptr.Here is a spoiler solution: