如何在 BST (C++) 中迭代计算节点数

How do you iteratively count nodes in a BST (C++)?

本文关键字:迭代 计算 节点 C++ BST      更新时间:2023-10-16

我已经知道如何递归地实现这个函数了。这是我所拥有的:

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

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

例如使用

stackqueue

顺便说一句。你可能想看看尾递归维基页面。

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