hashfun
unknown
plain_text
a year ago
3.1 kB
3
Indexable
#include <stdio.h> #include <stdlib.h> typedef struct Node { int data; struct Node *left, *right; } Node; Node *createNode(int data) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->data = data; newNode->left = newNode->right = NULL; return newNode; } void insert(Node **root, int data) { if (*root == NULL) *root = createNode(data); else insert((data < (*root)->data) ? &(*root)->left : &(*root)->right, data); } Node *search(Node *root, int key, Node **parent) { Node *current = root; while (current != NULL) { if (current->data == key) { printf("\nThe %d Element is Present", current->data); return current; } *parent = current; current = (key < current->data) ? current->left : current->right; } printf("\nData not present"); return NULL; } void inorder(Node *root) { if (root != NULL) { inorder(root->left); printf("%d ", root->data); inorder(root->right); } } void preorder(Node *root) { if (root != NULL) { printf("%d ", root->data); preorder(root->left); preorder(root->right); } } void postorder(Node *root) { if (root != NULL) { postorder(root->left); postorder(root->right); printf("%d ", root->data); } } int main() { char ans = 'N'; int choice, key; Node *root = NULL, *tmp, *parent; printf("\nProgram For Binary Search Tree "); do { printf("\n1.Create"); printf("\n2.Search"); printf("\n3.Recursive Traversals"); printf("\n4.Exit"); printf("\nEnter your choice: "); scanf("%d", &choice); switch (choice) { case 1: do { int data; printf("\nEnter The Element: "); scanf("%d", &data); insert(&root, data); printf("\nWant To Enter More Elements? (y/n): "); getchar(); // Consume the newline character ans = getchar(); } while (ans == 'y'); break; case 2: printf("\nEnter Element to be searched: "); scanf("%d", &key); tmp = search(root, key, &parent); if (tmp != NULL) printf("\nParent of node %d is %d", tmp->data, parent->data); break; case 3: if (root == NULL) printf("Tree Is Not Created"); else { printf("\nThe Inorder display: "); inorder(root); printf("\nThe Preorder display: "); preorder(root); printf("\nThe Postorder display: "); postorder(root); } break; } } while (choice != 4); return 0; }
Editor is loading...
Leave a Comment