简体   繁体   中英

Optimal binary tree search

I want to write a function that gets a root of a sorted binart tree and a value.

The function returns whether the value is in the tree or not.

A node in the binary tree looks like:

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
};

I've come with the following solution:

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;
}

Does anyone know of a more optimal solution?

Thanks!

The need of optimization comes when the code is heavily used and after applying metrics and analysing their results. Typically the only optimizations that are worthwhile are those that gain you an order of magnitude performance improvement in terms of speed.

All optimization is premature unless:

  1. A program is too slow.
  2. You have a measurement showing that the optimization could improve things.

So the answer in your case is: your code looks optimal enough for your needs and no optimization is required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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