Binary sort tree to find a recursive non-recursive

Algorithm thinking
first-searched keyword key compared with the root keyword t, if:
1) key = t, the root node address is returned;
2) key <t, then look for further left subtree;
3) key > t, then further to find the right subtree;


Corresponding to the following recursive algorithm:

BSTree SearchBST(BSTree bst, ElemType key) {
    if (!bst)
        return NULL;
    else if (bst->key == key)
        return bst;
    else if (bst->key > key)
        return SearchBST(bst->lchild, key);
    else
        return SearchBST(bst->rchild, key);
}

Corresponding to the non-recursive algorithm is as follows:

BSTNode *BST_Search(Bitree T, ElemType key, BSTNode *&p) {
    p = NULL;//p指向待查找结点的双亲,用于插入和删除操作中
    while(T!=NULL&&key!=T->data){
        if (key < T->data)
            T = T->lchild;
        else
            T = T->rchild;
    }
}

Guess you like

Origin www.cnblogs.com/brainstorm-yc/p/11774390.html
Recommended