简体   繁体   English

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

[英]Searching a Binary Search Tree, using counter for iterations

I have a function I'm using that searches for a number in a binary search tree. 我有一个正在使用的函数,该函数在二进制搜索树中搜索数字。 I use an external int that can be incremented by the function with each iteration, since the function calls itself if the number is not the root. 我使用一个外部int,该函数可以在每次迭代中递增,因为如果数字不是根,则函数会自行调用。

I'm just learning binary search trees, but I know there's a better way of doing it that I'm overlooking... using an int method that returns the counter for example, but I can't figure it out... 我只是在学习二进制搜索树,但我知道有一种更好的方法可以忽略……使用例如返回计数器的int方法,但我无法弄清楚……

edit: I know the number will definitely be in the BST, I just need to see how effective BST searching is vs. searching through an array for the same number. 编辑:我知道数字肯定会在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;
}
}

Your counter is counting the depth of the found element, not the number of elements in the tree. 您的计数器正在计算找到的元素的深度,而不是树中元素的数量。 If that is what you were looking for, then you're good. 如果那是您想要的,那么您就很好。

If you want to find out the number of elements, you need to do something like 如果要查找元素的数量,则需要执行以下操作

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

it really doesn't matter if you visit left or right first, you just want to visit all the nodes of interest. 首先访问左侧还是右侧并不重要,您只想访问所有感兴趣的节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM