Binarysingle Tree
Binarysingle Tree
class BST{
//properties
//operations
};
class BST{
//properties
//operations
};
Operations of BST
//constructor
BST(){
root=nullptr;
}
if (root == NULL) {
root = newNode;
return;
}
Another logic
}
//right sub tree
else{
if(temp->right!=nullptr)
temp=temp->right;
else{
temp->right=newNode;
break;
}
}
}
}
//private method
void insertNode(Node*& root, int val){
if(root ==nullptr){
root=new Node(val);
}
if(val==root->data){
return;
}
else if(val>root->data){
insertNode(root->right, val);
}
else{
insertNode(root->left, val);
}
}
//public method
void insertNode(int val){
insertNode(root, val);
}
//private method
Node* searchNode(Node* root, int key){
if(root==nullptr){
return root;
}
Node* temp=root;
while(!temp){
if(key==temp->data){
return temp;
}
else if(key>temp->data){
temp=temp->right;
}
else{
temp=temp->left;
}
}
return temp;
}
//public method
//private method
bool searchRecursion(Node* node, int key) {
if (node == nullptr) {
return false;
}
if (node->data == key) {
return true;
}
if (key < node->data) {
return searchRecursion(node->left, key);
}
return searchRecursion(node->right, key);
}
//public method
void searchRecursion(int key) {
bool flag= searchRecursion(root, key);
if(flag)
cout<<"Element found!!"<<endl;
else
cout<<"Element not found!!"<<endl;
}
//private method
void preorder(Node* root) {
if (root == nullptr) return;
cout << root->data << " "; // Visit the root
preorder(root->left); // Traverse left
preorder(root->right); // Traverse right
}
//public method
void preorder(){
preorder(root);
}
b. Inorder Traversal
//private method
void inorder(){
inorder(root);
}
c. Postorder Traversal
//private method
void postorder(Node* root) {
if (root == nullptr) return;
postorder(root->left); // Traverse left
postorder(root->right); // Traverse right
cout << root->data << " "; // Visit the root
}
//public method
void postorder(){
postorder(root);
}
//private methods
int height(Node* root) {
if (root == nullptr) {
return -1;
} else {
int lheight = height(root->left);
int rheight = height(root->right);
return (lheight > rheight) ? lheight + 1 : rheight + 1;
}
}
void printGivenLevel(Node* root, int level) {
if (root == nullptr) {
return;
} else if (level == 0) {
cout << root->data << " ";
} else {
printGivenLevel(root->left, level - 1);
printGivenLevel(root->right, level - 1);
}
}
7- Delete a node
//private method
Node* minValueNode(Node* node) {
Node* current = node;
while (current && current->left != nullptr) {
current = current->left;
}
return current;
}
return root;
}
//public method