#include <iostream>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node(int val) : data(val), left(nullptr), right(nullptr) {}
};
int countNodes(Node* root) {
if (root == nullptr) return 0; // base case: no node here
int leftCount = countNodes(root->left); // count nodes in left subtree
int rightCount = countNodes(root->right); // count nodes in right subtree
return 1 + leftCount + rightCount; // count current node plus children
}
int main() {
// build tree
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
int total = countNodes(root);
cout << "Total nodes = " << total << endl;
return 0;
}if (root == nullptr) return 0; // base case: no node here
stop counting when no node exists
int leftCount = countNodes(root->left); // count nodes in left subtree
count nodes in left subtree recursively
int rightCount = countNodes(root->right); // count nodes in right subtree
count nodes in right subtree recursively
return 1 + leftCount + rightCount; // count current node plus children
sum counts of left, right, and current node