0% found this document useful (0 votes)
28 views24 pages

Search Tree

The document provides C and Python implementations for Binary Search Trees (BST) and AVL Trees, detailing functions for insertion, searching, deletion, and traversal. It includes explanations of the algorithms and sample runs for user interaction with the trees. The document serves as a guide for understanding and implementing these data structures in programming.

Uploaded by

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

Search Tree

The document provides C and Python implementations for Binary Search Trees (BST) and AVL Trees, detailing functions for insertion, searching, deletion, and traversal. It includes explanations of the algorithms and sample runs for user interaction with the trees. The document serves as a guide for understanding and implementing these data structures in programming.

Uploaded by

lavanya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

#include <stdio.

h>

#include <stdlib.h>

// Define a node structure

typedef struct Node {

int data;

struct Node *left, *right;

} Node;

// Function to create a new node

Node* createNode(int value) {

Node* newNode = (Node*)malloc(sizeof(Node));

newNode->data = value;

newNode->left = newNode->right = NULL;

return newNode;

// Insert function

Node* insertNode(Node* root, int value) {

if (root == NULL) {

return createNode(value);

if (value < root->data)

root->left = insertNode(root->left, value);


else if (value > root->data)

root->right = insertNode(root->right, value);

return root;

// Find function

Node* findNode(Node* root, int value) {

if (root == NULL || root->data == value)

return root;

if (value < root->data)

return findNode(root->left, value);

return findNode(root->right, value);

// Find minimum node in the right subtree (for delete function)

Node* findMin(Node* root) {

while (root->left != NULL)

root = root->left;

return root;

// Delete function
Node* deleteNode(Node* root, int value) {

if (root == NULL) return root;

if (value < root->data)

root->left = deleteNode(root->left, value);

else if (value > root->data)

root->right = deleteNode(root->right, value);

else {

// Case 1: Node with only one child or no child

if (root->left == NULL) {

Node* temp = root->right;

free(root);

return temp;

} else if (root->right == NULL) {

Node* temp = root->left;

free(root);

return temp;

// Case 2: Node with two children

Node* temp = findMin(root->right);

root->data = temp->data;

root->right = deleteNode(root->right, temp->data);

return root;
}

// Inorder traversal (left-root-right)

void inorderTraversal(Node* root) {

if (root != NULL) {

inorderTraversal(root->left);

printf("%d ", root->data);

inorderTraversal(root->right);

// Main function

int main() {

Node* root = NULL;

int choice, value;

while (1) {

printf("\n1. Insert\n2. Search\n3. Delete\n4. Display\n5. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter value to insert: ");

scanf("%d", &value);
root = insertNode(root, value);

break;

case 2:

printf("Enter value to search: ");

scanf("%d", &value);

if (findNode(root, value))

printf("Found %d in the tree.\n", value);

else

printf("Value %d not found.\n", value);

break;

case 3:

printf("Enter value to delete: ");

scanf("%d", &value);

root = deleteNode(root, value);

break;

case 4:

printf("BST Inorder: ");

inorderTraversal(root);

printf("\n");

break;

case 5:

exit(0);

default:

printf("Invalid choice! Try again.\n");

}
}

return 0;

}
Steps to Implement BST in C:

1. Define a struct for the tree nodes.


2. Implement:
o Insertion (insertNode)
o Search (findNode)
o Deletion (deleteNode)
o Traversal (for displaying the tree)

Explanation of Functions:

1. Insertion (insertNode)
o Recursively finds the correct position and inserts the node.
2. Search (findNode)
o Recursively searches for a node with the given value.
3. Deletion (deleteNode)
o Handles three cases:
 Leaf node: Simply delete.
 One child: Replace with the child.
 Two children: Find the inorder successor (smallest node in the right
subtree), replace, and delete.
4. Inorder Traversal (inorderTraversal)
o Prints the tree in sorted order.
5. Main function
o Provides a menu for user input.

Sample Run
mathematica
Copy code
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter your choice: 1
Enter value to insert: 50

Enter your choice: 1


Enter value to insert: 30

Enter your choice: 1


Enter value to insert: 70

Enter your choice: 4


BST Inorder: 30 50 70

Enter your choice: 3


Enter value to delete: 30
avl serach tree how to implement in c programming laguage find,insert,delete

// C program to implement the avl tree

#include <stdio.h>

#include <stdlib.h>

// AVL Tree node

struct Node {

int key;

struct Node* left;

struct Node* right;

int height;

};

// Function to get height of the node

int getHeight(struct Node* n)

if (n == NULL)

return 0;

return n->height;

// Function to create a new node

struct Node* createNode(int key)

struct Node* node


= (struct Node*)malloc(sizeof(struct Node));

node->key = key;

node->left = NULL;

node->right = NULL;

node->height = 1; // New node is initially added at leaf

return node;

// Utility function to get the maximum of two integers

int max(int a, int b) { return (a > b) ? a : b; }

// Function to get balance factor of a node

int getBalanceFactor(struct Node* n)

if (n == NULL)

return 0;

return getHeight(n->left) - getHeight(n->right);

// Right rotation function

struct Node* rightRotate(struct Node* y)

struct Node* x = y->left;

struct Node* T2 = x->right;


// Perform rotation

x->right = y;

y->left = T2;

// Update heights

y->height

= max(getHeight(y->left), getHeight(y->right)) + 1;

x->height

= max(getHeight(x->left), getHeight(x->right)) + 1;

return x;

// Left rotation function

struct Node* leftRotate(struct Node* x)

struct Node* y = x->right;

struct Node* T2 = y->left;

// Perform rotation

y->left = x;

x->right = T2;

// Update heights

x->height
= max(getHeight(x->left), getHeight(x->right)) + 1;

y->height

= max(getHeight(y->left), getHeight(y->right)) + 1;

return y;

// Function to insert a key into AVL tree

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

// 1. Perform standard BST insertion

if (node == NULL)

return createNode(key);

if (key < node->key)

node->left = insert(node->left, key);

else if (key > node->key)

node->right = insert(node->right, key);

else // Equal keys are not allowed in BST

return node;

// 2. Update height of this ancestor node

node->height = 1

+ max(getHeight(node->left),

getHeight(node->right));
// 3. Get the balance factor of this ancestor node to

// check whether this node became unbalanced

int balance = getBalanceFactor(node);

// 4. If the node becomes unbalanced, then there are 4

// cases

// Left Left Case

if (balance > 1 && key < node->left->key)

return rightRotate(node);

// Right Right Case

if (balance < -1 && key > node->right->key)

return leftRotate(node);

// Left Right Case

if (balance > 1 && key > node->left->key) {

node->left = leftRotate(node->left);

return rightRotate(node);

// Right Left Case

if (balance < -1 && key < node->right->key) {

node->right = rightRotate(node->right);
return leftRotate(node);

// Return the (unchanged) node pointer

return node;

// Function to perform preorder traversal of AVL tree

void inOrder(struct Node* root)

if (root != NULL) {

inOrder(root->left);

printf("%d ", root->key);

inOrder(root->right);

// Main function

int main()

struct Node* root = NULL;

// Inserting nodes

root = insert(root, 1);

root = insert(root, 2);


root = insert(root, 4);

root = insert(root, 5);

root = insert(root, 6);

root = insert(root, 3);

// Print preorder traversal of the AVL tree

printf("Inorder traversal of AVL tree: ");

inOrder(root);

return 0;

Inorder traversal of AVL tree: 1 2 3 4 5 6


from collections import deque

class Node:

def __init__(self, key):

[Link] = key

[Link] = None

[Link] = None

class BST:

def __init__(self):

[Link] = None

def insert(self, key):

[Link] = self._insert_recursive([Link], key)

def _insert_recursive(self, node, key):

if node is None:

return Node(key)

if key < [Link]:

[Link] = self._insert_recursive([Link], key)

else:

[Link] = self._insert_recursive([Link], key)


return node

def find(self, key):

return self._find_recursive([Link], key)

def _find_recursive(self, node, key):

if node is None or [Link] == key:

return node

if key < [Link]:

return self._find_recursive([Link], key)

return self._find_recursive([Link], key)

def delete(self, key):

[Link] = self._delete_recursive([Link], key)

def _delete_recursive(self, node, key):

if node is None:

return node

if key < [Link]:

[Link] = self._delete_recursive([Link], key)

elif key > [Link]:

[Link] = self._delete_recursive([Link], key)

else:

if [Link] is None:

return [Link]
elif [Link] is None:

return [Link]

temp = self._min_value_node([Link])

[Link] = [Link]

[Link] = self._delete_recursive([Link], [Link])

return node

def _min_value_node(self, node):

current = node

while [Link] is not None:

current = [Link]

return current

def display(self, node, level=0, prefix="Root: "):

if node is not None:

print(" " * (level * 4) + prefix + str([Link]))

if [Link] or [Link]:

[Link]([Link], level + 1, "L--- ")

[Link]([Link], level + 1, "R--- ")

# User Input for BST

bst = BST()

while True:

print("\nBinary Search Tree Operations:")

print("1. Insert\n2. Delete\n3. Find\n4. Display\n5. Exit")


choice = int(input("Enter your choice: "))

if choice == 1:

key = int(input("Enter value to insert: "))

[Link](key)

elif choice == 2:

key = int(input("Enter value to delete: "))

[Link](key)

elif choice == 3:

key = int(input("Enter value to find: "))

if [Link](key):

print(f"Key {key} found in BST.")

else:

print(f"Key {key} not found.")

elif choice == 4:

print("\nHierarchical Structure of BST:")

[Link]([Link])

elif choice == 5:

break

else:

print("Invalid choice! Please try again.")


Avl

class Node:

def __init__(self, key):

[Link] = key

[Link] = None

[Link] = None

[Link] = 1

class AVLTree:

def __init__(self):

[Link] = None

def insert(self, key):

[Link] = self._insert_recursive([Link], key)

def _insert_recursive(self, node, key):

if not node:

return Node(key)

if key < [Link]:

[Link] = self._insert_recursive([Link], key)

else:

[Link] = self._insert_recursive([Link], key)


[Link] = 1 + max(self._get_height([Link]), self._get_height([Link]))

return self._balance(node)

def delete(self, key):

[Link] = self._delete_recursive([Link], key)

def _delete_recursive(self, node, key):

if not node:

return node

if key < [Link]:

[Link] = self._delete_recursive([Link], key)

elif key > [Link]:

[Link] = self._delete_recursive([Link], key)

else:

if not [Link]:

return [Link]

elif not [Link]:

return [Link]

temp = self._min_value_node([Link])

[Link] = [Link]

[Link] = self._delete_recursive([Link], [Link])

[Link] = 1 + max(self._get_height([Link]), self._get_height([Link]))

return self._balance(node)
def _balance(self, node):

balance_factor = self._get_balance(node)

if balance_factor > 1:

if self._get_balance([Link]) < 0:

[Link] = self._rotate_left([Link])

return self._rotate_right(node)

if balance_factor < -1:

if self._get_balance([Link]) > 0:

[Link] = self._rotate_right([Link])

return self._rotate_left(node)

return node

def _rotate_left(self, z):

y = [Link]

T2 = [Link]

[Link] = z

[Link] = T2

[Link] = 1 + max(self._get_height([Link]), self._get_height([Link]))

[Link] = 1 + max(self._get_height([Link]), self._get_height([Link]))

return y

def _rotate_right(self, z):

y = [Link]

T3 = [Link]

[Link] = z
[Link] = T3

[Link] = 1 + max(self._get_height([Link]), self._get_height([Link]))

[Link] = 1 + max(self._get_height([Link]), self._get_height([Link]))

return y

def _get_height(self, node):

return [Link] if node else 0

def _get_balance(self, node):

return self._get_height([Link]) - self._get_height([Link]) if node else 0

def _min_value_node(self, node):

current = node

while [Link]:

current = [Link]

return current

def display(self, node, level=0, prefix="Root: "):

if node is not None:

print(" " * (level * 4) + prefix + str([Link]))

if [Link] or [Link]:

[Link]([Link], level + 1, "L--- ")

[Link]([Link], level + 1, "R--- ")

# User Input for AVL Tree


avl = AVLTree()

while True:

print("\nAVL Tree Operations:")

print("1. Insert\n2. Delete\n3. Display\n4. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:

key = int(input("Enter value to insert: "))

[Link](key)

elif choice == 2:

key = int(input("Enter value to delete: "))

[Link](key)

elif choice == 3:

print("\nHierarchical Structure of AVL Tree:")

[Link]([Link])

elif choice == 4:

break

else:

print("Invalid choice! Please try again.")

You might also like