bst.c

trees Implementation

55 lines
1153 bytes
C
1#include <stdio.h>
2#include <stdlib.h>
3
4struct Node {
5    int key;
6    struct Node *left, *right;
7};
8
9// Create a new BST node
10struct Node* newNode(int item) {
11    struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
12    temp->key = item;
13    temp->left = temp->right = NULL;
14    return temp;
15}
16
17// Inorder traversal
18void inorder(struct Node* root) {
19    if (root != NULL) {
20        inorder(root->left);
21        printf("%d ", root->key);
22        inorder(root->right);
23    }
24}
25
26// Insert a new node
27struct Node* insert(struct Node* node, int key) {
28    // If the tree is empty, return a new node
29    if (node == NULL) return newNode(key);
30
31    // Otherwise, recur down the tree
32    if (key < node->key)
33        node->left = insert(node->left, key);
34    else if (key > node->key)
35        node->right = insert(node->right, key);
36
37    return node;
38}
39
40int main() {
41    struct Node* root = NULL;
42    root = insert(root, 50);
43    insert(root, 30);
44    insert(root, 20);
45    insert(root, 40);
46    insert(root, 70);
47    insert(root, 60);
48    insert(root, 80);
49
50    printf("Inorder traversal of the given tree: \n");
51    inorder(root);
52
53    return 0;
54}
55