Day 20: (Binary Search Tree)

Search given Key in BST Solved on: Aug 5th 2020

TreeNode* searchBST(TreeNode* root, int val) {
    if (root == NULL) {
        return NULL;
    }

    if (val > root->val) {
        return searchBST(root->right, val);
    } else if (val < root->val) {
        return searchBST(root->left, val);
    } else if (root->val == val) {
        return root;
    }
    return NULL;
}

Find the inorder predecessor/successor of a given Key in BST. Solved on Aug 6th 2020

void findPreSuc(Node* root, Node*& pre, Node*& suc, int key) {
    if (root==NULL) {
        return ;
    }
    if (root->key == key) {
        if (root->right != NULL) {
            Node *temp = root->right;
            while (temp->left){
                temp=temp->left;
            }
            suc = temp;
        }
        if (root->left != NULL) {
            Node *temp = root->left;
            while (temp->right){
                temp=temp->right;
            }
            pre = temp;
        }
        return ;
    }
    if (key < root->key) {
        suc = root;
        findPreSuc(root->left,pre, suc, key);
    } else {
        pre = root;
        findPreSuc(root->right,pre, suc, key);
    }
}

Last updated

Was this helpful?