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;
}

iterative method(not recursion function) count nodes in binary tree c++SolutionTo implement a node counter of a binary tree without recursion, you should be abl

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site