搜索二进制搜索树,使用计数器进行迭代

时间:2013-07-12 13:56:20

标签: c binary-search-tree

我有一个函数我用它搜索二叉搜索树中的数字。我使用一个外部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;
}
}

1 个答案:

答案 0 :(得分:0)

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

如果您想了解元素的数量,您需要执行类似

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

如果您先向左或向右访问真的没关系,您只想访问所有感兴趣的节点。