[英]Optimal binary tree search
我想编写一个函数来获取已排序的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 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;
}
有谁知道更优化的解决方案?
谢谢!
当代码被大量使用并且在应用度量并分析其结果之后,需要进行优化。 通常,唯一值得的优化是那些能够在速度方面获得一个数量级性能提升的优化。
因此,您的答案就是: 您的代码看起来足够满足您的需求,无需进行优化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.