Anda di halaman 1dari 4

Nama : Muhammad Zikra

NIM : 220170030
Kelas : A3 Struktur Data
Prodi : Teknik Informatika
Project 3

1. Pseucode BST

Class node
properties:
key
left
right

constructor(key):
set key to given key
set left and right to null

Class binarysearchtree
property:
root

constructor:
set root to null

function insert(root, key):


if root is null:
create a new node with the given key
return the new node

if key is less than root's key:


set root's left child to insert(root's left child, key)
else if key is greater than root's key:
set root's right child to insert(root's right child, key)

return the root

function insert(key):
set root to insert(root, key)

function inordertraversal(root):
if root is not null:
perform inordertraversal(root's left child)
print root's key
perform inordertraversal(root's right child)
function inordertraversal():
perform inordertraversal(root)

2. Listing Program

#include <iostream>

class Node {
public:
int key;
Node* left;
Node* right;

Node(int k) : key(k), left(nullptr), right(nullptr) {}


};

class BST {
private:
Node* root;

Node* insert(Node* root, int key) {


if (root == nullptr) {
return new Node(key);
}

if (key < root->key) {


root->left = insert(root->left, key);
} else if (key > root->key) {
root->right = insert(root->right, key);
}

return root;
}
void inorderTraversal(Node* root) {
if (root != nullptr) {
inorderTraversal(root->left);
std::cout << root->key << " ";
inorderTraversal(root->right);
}
}

public:
BST() : root(nullptr) {}

void insert(int key) {


root = insert(root, key);
}

void inorderTraversal() {
inorderTraversal(root);
std::cout << std::endl;
}
};

int main() {
BST bst;

// Memasukkan angka yang diberikan


bst.insert(30);
bst.insert(20);
bst.insert(10);
bst.insert(15);
bst.insert(25);

std::cout << "Inorder Traversal: ";


bst.inorderTraversal();

return 0;
3. Contoh Proking

Anggap kita memasukkan angka 30, 20, 10, 15, dan 25 ke dalam BST dalam urutan tersebut.
Pohon BST akan terlihat seperti berikut:

30
/
20
/\
10 25
/
15

Pohon ini mencerminkan sifat BST, di mana setiap simpul memiliki anak kiri dengan nilai
yang kurang dari dirinya dan anak kanan dengan nilai yang lebih besar. Gambaran ini dapat
membantu Anda memvisualisasikan struktur pohon berdasarkan pseudocode yang telah
diberikan.

Anda mungkin juga menyukai