0% found this document useful (0 votes)
6 views5 pages

BST

The document provides implementations for inserting and deleting nodes in a Binary Search Tree (BST) using both iterative and recursive methods. It also includes a function to find the in-order successor of a node in the BST. Key operations include handling tree structure adjustments during insertions and deletions while maintaining the properties of the BST.

Uploaded by

Fatima Arshad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views5 pages

BST

The document provides implementations for inserting and deleting nodes in a Binary Search Tree (BST) using both iterative and recursive methods. It also includes a function to find the in-order successor of a node in the BST. Key operations include handling tree structure adjustments during insertions and deletions while maintaining the properties of the BST.

Uploaded by

Fatima Arshad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Insert in a Binary Search Tree - Iterative

Node* insert(Node* root, int key)


{ Node* newnode = new Node(key);
Node* p = NULL;

if (root=NULL){
root= newnode;
p = root;
}
else{
Node* curr = root;
while (curr != NULL) {
p = x;
if (key < curr->key)
curr = cutt->left;
else
curr = curr->right;
}

if (key < p->key)


p->left = newnode;
else
p->right = newnode;
}
return p;
}
Insert in a Binary Search Tree - Recursive

Node* insert(Node* node, int key) {

// If the tree is empty, return a new node


if (node == NULL)
return new Node(key);
else if (key > node->data)
node->right = insert(node->right, key);
else
node->left = insert(node->left, key);
return node;
}
Deletion in a BST
Node* delNode(Node* root, int x) {
if (root==NULL)
return root;
if (x < root->key)
root->left = delNode(root->left, x);
else if (x > root->key)
root->right = delNode(root->right, x);
else { // found x
if (root->left == NULL) {
Node *temp = root->right;
delete root;
return temp;
}
if (root->right == NULL){
Node *temp = root->left;
delete root;
return temp;
}

// if both subtrees
Node *succ = getSuccessor(root);
root->key = succ->key;
root->right=delNode(root->root->right,succ->key);
}
return root;
}
Find Successor of a node

In-order Successor is left most child of right subtree.


Node *getSuccessor(Node *c){
c = c->right;
While (c!=NULL && c->left!=NULL)
C = c->left;

Return c;
}

You might also like