如何迭代计算BST(C ++)中的节点?

时间:2016-03-14 21:42:25

标签: c++ count iteration binary-search-tree nodes

我已经知道如何递归地实现这个功能。这就是我所拥有的:

int nodeCount(node *root){
    if(root == NULL)
        return 0;
    return 1 + nodeCount(root->left) + nodeCount(root->right);
}

我现在想要在没有递归的情况下执行节点计数。

1 个答案:

答案 0 :(得分:1)

例如,使用stackqueue

顺便说一下。您可能需要查看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;
}