BST Code Implementation
BST Code Implementation
Code:
#include <iostream>
using namespace std;
delete root;
root = nullptr;
} else if (root->left == nullptr) {
// Agar sirf right child ho to root ko update karein
Node* temp = root;
root = root->right;
delete temp;
} else if (root->right == nullptr) {
// Agar sirf left child ho to root ko update karein
Node* temp = root;
root = root->left;
delete temp;
} else {
// Agar dono child ho to in-order successor dhundhein
Node* successor = root->right;
while (successor->left != nullptr) {
successor = successor->left;
}
root->data = successor->data; // Root ki value successor se
replace karein
delNode(root->right, successor->data); // Successor ko delete
karein
}
}
}
int main() {
Node* root = nullptr; // Tree ka root node
// Different traversals
cout << "Inorder Traversal: ";
inorderTraversal(root);
cout << endl;
return 0;
}
Output:
Algorithm:
1. Structure Definition
• Define a Node structure with:
o data: stores the value.
o left: pointer to the left child.
o right: pointer to the right child.
2. Create Node
• Input: Reference to a Node pointer and a value val.
• Process:
o Allocate memory for a new Node.
o Initialize data with val and left/right as nullptr.
• Output: A new node is created.
3. Insert Node
• Input: Reference to the root node and a value val.
• Process:
o If the tree is empty, create a new node at the root.
o Otherwise:
▪ If val is less than root->data, insert into the left subtree.
▪ Otherwise, insert into the right subtree.
• Output: The tree is updated with the new node.
4. Search Node
• Input: Root node and a value val.
• Process:
Name: Wishaq Akbar Reg #: 2023-BS-AI-041
Diagram: