Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdlib>
- #include <ctime>
- using namespace std;
- // Mendefinisikan konstanta untuk ukuran maksimum array
- const int MAX_SIZE = 40;
- // Definisi struktur Node BST
- struct Node {
- int data;
- Node *left;
- Node *right;
- Node(int);
- };
- // Definisi class Tree
- struct Tree {
- Node *root;
- int nodeCount;
- int arrayIndex;
- Node *nodes[MAX_SIZE];
- Tree();
- void insertNode(int);
- void preorderTraversal();
- void inorderTraversal();
- void postorderTraversal();
- private:
- void insert(Node *, int);
- void preorder(Node *);
- void inorder(Node *);
- void postorder(Node *);
- };
- Node::Node(int dt) {
- data = dt;
- left = right = NULL;
- }
- Tree::Tree() {
- root = NULL;
- nodeCount = 0;
- arrayIndex = 0;
- }
- // Method untuk menyisipkan node baru ke dalam BST
- void Tree::insertNode(int dt) {
- if (nodeCount >= 10 || arrayIndex >= MAX_SIZE)
- return;
- if (root == NULL) {
- root = new Node(dt);
- nodes[arrayIndex++] = root;
- nodeCount++;
- } else {
- insert(root, dt);
- }
- }
- // Fungsi rekursif untuk menyisipkan node baru ke dalam BST
- void Tree::insert(Node *node, int dt) {
- if (dt < node->data) {
- if (node->left == NULL && arrayIndex < MAX_SIZE) {
- node->left = new Node(dt);
- nodes[arrayIndex++] = node->left;
- nodeCount++;
- } else {
- insert(node->left, dt);
- }
- }
- else if (dt > node->data) {
- if (node->right == NULL && arrayIndex < MAX_SIZE) {
- node->right = new Node(dt);
- nodes[arrayIndex++] = node->right;
- nodeCount++;
- } else {
- insert(node->right, dt);
- }
- }
- }
- void Tree::preorderTraversal() {
- preorder(root);
- }
- void Tree::inorderTraversal() {
- inorder(root);
- }
- void Tree::postorderTraversal() {
- postorder(root);
- }
- void Tree::preorder(Node *node) {
- if (node == NULL)
- return;
- cout << node->data << ", ";
- preorder(node->left);
- preorder(node->right);
- }
- void Tree::inorder(Node *node) {
- if (node == NULL)
- return;
- inorder(node->left);
- cout << node->data << ", ";
- inorder(node->right);
- }
- void Tree::postorder(Node *node) {
- if (node == NULL)
- return;
- postorder(node->left);
- postorder(node->right);
- cout << node->data << ", ";
- }
- // Fungsi utama
- int main() {
- // Membuat objek Tree
- Tree *tree = new Tree();
- int value;
- cout << "Masukkan nilai data berikut: " << endl;
- // Menghasilkan dan menyisipkan 10 bilangan acak dari 0-99 ke dalam BST
- srand(time(NULL));
- for (int i = 0; i < 10; i++) {
- value = rand() % 100;
- cout << value << " ";
- tree->insertNode(value);
- }
- // Traversal BST
- cout << "\n\nPreorder Traversal" << endl;
- tree->preorderTraversal();
- cout << "\n\nInorder Traversal" << endl;
- tree->inorderTraversal();
- cout << "\n\nPostorder Traversal" << endl;
- tree->postorderTraversal();
- delete tree;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement