【问题标题】:Searching a Binary Search Tree, using counter for iterations搜索二叉搜索树,使用计数器进行迭代
【发布时间】:2013-07-12 13:56:19
【问题描述】:

我正在使用一个在二叉搜索树中搜索数字的函数。我使用了一个外部 int,它可以在每次迭代时由函数递增,因为如果数字不是根,函数会调用自己。

我只是在学习二叉搜索树,但我知道有一个更好的方法可以做到这一点,我忽略了......例如使用返回计数器的 int 方法,但我无法弄清楚。 ..

编辑: 我知道数字肯定会在 BST 中,我只需要看看 BST 搜索与通过数组搜索相同数字的效果如何。

// This external int can be incremented by the searchBST function 
// to keep track of iterations

int bcounter = 0;

// Search Binary Search Tree function

node* searchBST(node ** tree, int num){

bcounter++;

if(num < (*tree)->data) {
    searchBST(&((*tree)->left), num);
}
else 
    if(num > (*tree)->data) {
    searchBST(&((*tree)->right), num);
}
else 
    if(num == (*tree)->data) {
    return *tree;
}
}

【问题讨论】:

  • 不是您问题的答案,但您希望在 if 语句中两次调用 searchBST 之前有“返回”。
  • 但是,关于你的问题,你说有更好的方法来做“它”。你是什​​么意思?你想做什么更好?如果是计数,您可以将其作为参数传递,或将其设为函数内的静态变量。

标签: c binary-search-tree


【解决方案1】:

您的计数器计算的是找到元素的深度,而不是树中元素的数量。如果这就是你要找的东西,那么你很好。

如果你想找出元素的数量,你需要做类似的事情

if (node is not null) {
  // count this node, it is not null
  count++;
  visit(node left);
  visit(node right);
}

先访问左还是右并不重要,你只想访问所有感兴趣的节点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 2017-05-09
    相关资源
    最近更新 更多