C 最优二叉树搜索
我想写一个函数,它获取一个已排序的binart树的根和一个值 函数返回值是否在树中 二叉树中的节点如下所示:C 最优二叉树搜索,c,data-structures,binary-search-tree,C,Data Structures,Binary Search Tree,我想写一个函数,它获取一个已排序的binart树的根和一个值 函数返回值是否在树中 二叉树中的节点如下所示: struct Node { int key; // Contains the key in the current node Node* right; // Right subtree. All nodes in it will be GREATER than the current. May be NULL Node* left; // Left subtre
struct Node {
int key; // Contains the key in the current node
Node* right; // Right subtree. All nodes in it will be GREATER than the current. May be NULL
Node* left; // Left subtree. All nodes in it will be SMALLER than the current. May be NULL
};
我提供了以下解决方案:
bool searchBinaryTree(int value, Node* root) {
Node* currNode = root;
while(currNode) {
if((currNode->key) < value) {
currNode = currNode->right;
} else if((currNode->key) > value) {
currNode = currNode->left;
} else {
return true;
}
}
return false;
}
boolsearchbarytree(int值,节点*根){
节点*currNode=根节点;
while(currende){
if((currNode->key)right;
}else if((currNode->key)>值){
currNode=currNode->left;
}否则{
返回true;
}
}
返回false;
}
有人知道更理想的解决方案吗
谢谢
当大量使用代码时,以及在应用度量和分析结果之后,需要进行优化。通常,唯一值得进行的优化是那些在速度方面为您带来一个数量级性能改进的优化
所有优化都是过早的,除非:
因此,在您的情况下,答案是:您的代码看起来足够适合您的需要,无需进行优化。使用递归可以实现上述功能:即
而循环可以由函数调用代替,但我不知道复杂度是否会更低。这可能是每个节点的最佳选择。有三种可能:您要查找的值可以位于左子节点、右子节点,或者您已经找到了要查找的机器人。这就是这个函数的作用。进一步优化:唯一的外部变量是二叉树的构造。如果你能完美地(或尽可能地)平衡它,你的整体表现就会提高。。。他可以忽略性能,去和一些生活在云中的计算机科学家或数学人交谈。然后,他们会建议使用递归,这在现实世界中会导致所有性能的彻底破坏,同时使编译器很难(如果不是不可能的话)优化代码,这取决于是否/如何处理递归展开。这里有很多未成熟的东西,不仅仅是手动优化。