iterative methodnot recursion function count nodes in binary
iterative method(not recursion function) count nodes in binary tree c++
Solution
To implement a node counter of a binary tree without recursion, you should be able to use a stack.
Here is the sample code for you:
int countNodesInBinaryTree(Node *root)
{
int count = 0;
stack<Node*> stackVector;
stackVector.push(root);
while (stackVector.size() > 0)
{
Node *topNode = stackVector.top();
stackVector.pop();
if (topNode != NULL)
{
count++;
stackVector.push(topNode->left);
stackVector.push(topNode->right);
}
}
return count;
}
