74просмотров
77.9%от подписчиков
5 ноября 2025 г.
Score: 81
BST (Binary Search Tree)
#include <stdio.h>
#include <stdlib.h> struct Node { int data; struct Node left; struct Node right;
}; // Create a new node
struct Node createNode(int data) { struct Node newNode = (struct Node)malloc(sizeof(struct Node)); newNode->data = data; newNode->left = newNode->right = NULL; return newNode;
} // Insert a value into BST
struct Node insert(struct Node root, int data) { if (root == NULL) return createNode(data); if (data < root->data) root->left = insert(root->left, data); else if (data > root->data) root->right = insert(root->right, data); return root;
} // Inorder traversal (prints sorted values)
void inorder(struct Node root) { if (root != NULL) { inorder(root->left); printf("%d ", root->data); inorder(root->right); }
} int main() { struct Node* root = NULL; // Insert some elements root = insert(root, 8); insert(root, 3); insert(root, 10); insert(root, 1); insert(root, 6); insert(root, 14); insert(root, 4); insert(root, 7); insert(root, 13); printf("Inorder traversal of BST:\n"); inorder(root); printf("\n"); return 0;
}