我已经知道如何递归地实现这个功能。这就是我所拥有的:
int nodeCount(node *root){
if(root == NULL)
return 0;
return 1 + nodeCount(root->left) + nodeCount(root->right);
}
我现在想要在没有递归的情况下执行节点计数。
答案 0 :(得分:1)
例如,使用stack
或queue
。
顺便说一下。您可能需要查看Tail recursion wiki page。
int nodeCount(node * root)
{
int counter = 0;
stack<node*> v; // a container with remaining nodes "to check"
v.push(root); // first node "to check"
while (v.size() > 0) // while there is something "to check"
{
node * n = v.top(); // take element from the top of stack
v.pop(); // remove that element from the top of stack
if (n != NULL) // if node is valid
{
counter++; // count it
v.push(n->left); // and add
v.push(n->right); // his children to the stack
}
}
return counter;
}