🌳 Tree dan Binary Tree

Struktur Data dan Algoritma

Pertemuan 11

Universitas Pertahanan RI

🎯 Tujuan Pembelajaran

Setelah pertemuan ini, mahasiswa mampu:

  1. Menjelaskan terminologi dan konsep dasar tree
  2. Mengidentifikasi jenis-jenis binary tree
  3. Membandingkan representasi linked structure dan array
  4. Mengimplementasikan traversal: preorder, inorder, postorder
  5. Menerapkan level-order traversal menggunakan queue
  6. Membangun expression tree

📋 Agenda

Bagian 1

  1. Pengantar Tree
  2. Terminologi Tree
  3. Binary Tree
  4. Jenis-jenis Binary Tree
  5. Representasi Binary Tree

Bagian 2

  1. Preorder Traversal
  2. Inorder Traversal
  3. Postorder Traversal
  4. Level-order Traversal
  5. Expression Tree

📖 1. Pengantar Tree

Tree adalah struktur data non-linear yang terdiri dari node-node yang terhubung secara hierarkis.

Setiap tree memiliki:

  • Satu node khusus: root (akar)
  • Setiap node dapat memiliki 0 atau lebih child

🆚 Tree vs Struktur Linear

Aspek Array/List Tree
Struktur Linear Hierarkis (non-linear)
Hubungan Predecessor-Successor Parent-Child
Searching O(n) unsorted O(log n) BST seimbang
Representasi Flat Berlevel

🎖️ Aplikasi Tree

📁 File System

Struktur folder & file

🏛️ Organisasi

Hierarki komando militer

🎯 Decision Tree

Analisis ancaman taktis

💾 Database

B-Tree indexing

🔧 Parsing

Expression tree

🤖 AI/ML

Decision tree classifier

📖 2. Terminologi Tree

A
╱ ╲
B C
╱ ╲      ╱ ╲
D E F G

Contoh binary tree dengan 7 node

Komponen Dasar Tree

Istilah Definisi
Root Node paling atas tanpa parent
Parent Node yang memiliki child di bawahnya
Child Node yang memiliki parent di atasnya
Sibling Node-node dengan parent yang sama
Leaf Node tanpa child (terminal)
Internal Node Node yang bukan leaf (punya child)

Properti Ukuran Tree

Properti Definisi Contoh
Depth Jumlah edge dari root ke node Depth(A)=0, Depth(D)=2
Height Jumlah edge terpanjang ke leaf Height(A)=2, Height(D)=0
Level Semua node dengan depth sama Level 0: {A}
Degree Jumlah child dari node Degree(A)=2

🧠 Quiz: Terminologi

10
╱ ╲
5 15
╱        ╲
3 20

Tentukan: leaves, height, depth node 15!

  • Leaves: 3, 20
  • Height tree: 2
  • Depth node 15: 1

📖 3. Binary Tree

Binary Tree adalah tree di mana setiap node memiliki maksimal 2 child — disebut left child dan right child.


struct Node {
    int data;
    Node* left;   // Pointer ke left child
    Node* right;  // Pointer ke right child
    
    Node(int val) : data(val), left(nullptr), right(nullptr) {}
};
                        

📊 Jenis-jenis Binary Tree

Full Binary Tree

Setiap node punya 0 atau 2 child

A
╱ ╲
B C
╱ ╲
D E

Complete Binary Tree

Semua level penuh kecuali terakhir (kiri ke kanan)

A
╱ ╲
B C
╱ ╲
D E

📊 Jenis Binary Tree (lanjutan)

Perfect Binary Tree

Semua level terisi penuh

n = 2h+1 - 1

A
╱ ╲
B C
╱ ╲ ╱ ╲
D E F G

Skewed Binary Tree

Semua node hanya punya satu child

A
B
C

Worst case: O(n)!

📐 Properti Matematis Binary Tree

Properti Formula
Max nodes di level l 2l
Max nodes dengan height h 2h+1 - 1
Min height dengan n nodes ⌈log₂(n+1)⌉ - 1
Jumlah leaf (perfect tree) 2h

📖 4. Representasi Binary Tree

🔗 Linked Structure

  • Menggunakan pointer
  • Fleksibel
  • Cocok untuk general tree

📊 Array

  • Index-based
  • Efisien untuk complete tree
  • Cocok untuk Heap

💻 Linked Structure Implementation


struct Node {
    int data;
    Node* left;
    Node* right;
    Node(int val) : data(val), left(nullptr), right(nullptr) {}
};

class BinaryTree {
private:
    Node* root;
public:
    BinaryTree() : root(nullptr) {}
    Node* getRoot() { return root; }
    void setRoot(Node* node) { root = node; }
};

// Penggunaan
int main() {
    BinaryTree tree;
    tree.setRoot(new Node(10));
    tree.getRoot()->left = new Node(5);
    tree.getRoot()->right = new Node(15);
}
                    

📊 Array Representation

10 [0]
╱ ╲
5 [1] 15 [2]
╱ ╲    ╱ ╲
3 [3] 7 [4] 12 [5] 20 [6]

Array: [10, 5, 15, 3, 7, 12, 20]

🔢 Formula Indexing (0-based)

Relasi Formula
Parent dari node i (i - 1) / 2
Left child dari node i 2 * i + 1
Right child dari node i 2 * i + 2

💡 Contoh: Node index 2 (nilai 15)

Left child: 2*2+1 = 5 → arr[5] = 12

⚖️ Perbandingan Representasi

Aspek Linked Array
Memory Fleksibel Fixed/resize
Akses parent Perlu pointer tambahan O(1) formula
Insertion Mudah Sulit jika tidak complete
Wasted space Tidak ada Ada jika sparse
Best for General tree Complete tree, Heap

📖 5. Tree Traversal

Traversal adalah proses mengunjungi semua node dalam tree dengan urutan tertentu.

Jenis Traversal:

Depth-First (DFS):

  • Preorder
  • Inorder
  • Postorder

Breadth-First (BFS):

  • Level-order

🔄 Preorder Traversal

Urutan: Root → Left → Right

A
╱ ╲
B C
╱ ╲    ╱ ╲
D E F G
A B D E C F G

💻 Preorder Implementation

Rekursif


void preorder(Node* root) {
    if (root == nullptr) return;
    
    cout << root->data << " ";
    preorder(root->left);
    preorder(root->right);
}
                            

Iteratif (Stack)


void preorderIterative(Node* root) {
    if (!root) return;
    stack s;
    s.push(root);
    
    while (!s.empty()) {
        Node* curr = s.top();
        s.pop();
        cout << curr->data << " ";
        
        if (curr->right) s.push(curr->right);
        if (curr->left) s.push(curr->left);
    }
}
                            

🔄 Inorder Traversal

Urutan: Left → Root → Right

📌 Untuk BST: menghasilkan urutan terurut!

A
╱ ╲
B C
╱ ╲    ╱ ╲
D E F G
D B E A F C G

💻 Inorder Implementation


void inorder(Node* root) {
    if (root == nullptr) return;
    
    inorder(root->left);         // Traverse subtree kiri
    cout << root->data << " ";   // Kunjungi root
    inorder(root->right);        // Traverse subtree kanan
}
                    

💡 Kegunaan Inorder:

  • Mendapatkan elemen BST secara terurut
  • Evaluasi ekspresi infix

🔄 Postorder Traversal

Urutan: Left → Right → Root

📌 Berguna untuk menghapus tree (delete children dulu)

A
╱ ╲
B C
╱ ╲    ╱ ╲
D E F G
D E B F G C A

💻 Postorder Implementation


void postorder(Node* root) {
    if (root == nullptr) return;
    
    postorder(root->left);       // Traverse subtree kiri
    postorder(root->right);      // Traverse subtree kanan
    cout << root->data << " ";   // Kunjungi root
}

// Untuk menghapus tree dengan aman
void deleteTree(Node* root) {
    if (root == nullptr) return;
    
    deleteTree(root->left);
    deleteTree(root->right);
    delete root;  // Hapus setelah children dihapus
}
                    

🔄 Level-order Traversal (BFS)

Urutan: Level by level, kiri ke kanan

📌 Menggunakan Queue

A Level 0
╱ ╲
B C Level 1
╱ ╲    ╱ ╲
D E F G Level 2
A B C D E F G

💻 Level-order Implementation


#include 

void levelOrder(Node* root) {
    if (root == nullptr) return;
    queue q;
    q.push(root);
    
    while (!q.empty()) {
        Node* current = q.front();
        q.pop();
        
        cout << current->data << " ";
        
        if (current->left) q.push(current->left);
        if (current->right) q.push(current->right);
    }
}
                    

📊 Perbandingan Traversal

Traversal Urutan Kegunaan
Preorder Root → L → R Copy tree, prefix notation
Inorder L → Root → R BST sorted, infix notation
Postorder L → R → Root Delete tree, postfix notation
Level-order Level by level Print by level, BFS

Kompleksitas: Semua O(n) waktu, O(h) atau O(w) ruang

🧠 Quiz: Traversal

1
╱ ╲
2 3
╱ ╲     ╲
4 5 6

Tuliskan hasil Preorder, Inorder, dan Postorder!

  • Preorder: 1, 2, 4, 5, 3, 6
  • Inorder: 4, 2, 5, 1, 3, 6
  • Postorder: 4, 5, 2, 6, 3, 1

📖 6. Expression Tree

Expression Tree adalah binary tree yang merepresentasikan ekspresi matematika.

  • Leaf nodes: Operand (angka/variabel)
  • Internal nodes: Operator (+, -, *, /)

Contoh: (3 + 5) * 2

*
╱ ╲
+ 2
╱ ╲
3 5
Preorder (Prefix): * + 3 5 2
Inorder (Infix): 3 + 5 * 2
Postorder (Postfix): 3 5 + 2 *

💻 Build Expression Tree dari Postfix


Node* buildExpressionTree(string postfix) {
    stack st;
    
    for (char c : postfix) {
        if (c == ' ') continue;
        
        Node* node = new Node(c);
        
        if (isdigit(c) || isalpha(c)) {
            // Operand: langsung push
            st.push(node);
        } else {
            // Operator: pop 2 operand sebagai children
            node->right = st.top(); st.pop();
            node->left = st.top(); st.pop();
            st.push(node);
        }
    }
    
    return st.top();  // Root dari expression tree
}
                    

🎖️ 7. Aplikasi Pertahanan

Decision Tree untuk Analisis Ancaman

Kecepatan > 500?
╱ ╲
Ketinggian
> 10km?
Sipil
╱ ╲
Jet Tempur Rudal!

🎖️ Hierarki Komando

Panglima
╱ ╲
Kodam A Kodam B
╱ ╲      ╱ ╲
Brigif 1 Brigif 2 Brigif 3 Brigif 4

Kegunaan: Representasi struktur organisasi, distribusi perintah, analisis jalur komando

📝 Ringkasan

Konsep Deskripsi Kompleksitas
Tree Struktur hierarkis dengan root, parent, child -
Binary Tree Max 2 children per node -
Preorder Root → Left → Right O(n)
Inorder Left → Root → Right (sorted for BST) O(n)
Postorder Left → Right → Root (delete tree) O(n)
Level-order BFS menggunakan Queue O(n)
Expression Tree Representasi ekspresi matematika O(n)

❓ Pertanyaan?

Silakan bertanya atau diskusi

Referensi: Cormen Ch.12 | Weiss Ch.4 | Hubbard Ch.9-10

Terima Kasih! 🙏

Struktur Data dan Algoritma

Pertemuan 11: Tree dan Binary Tree

© 2026 - CC BY 4.0