2. Tree Concept

2.1 Basic Theory

2.1.1 Definition of a Tree

image

A Tree is a non-linear hierarchical data structure composed of nodes and edges.

2.1.2 Important Terms in a Tree

image

2.1.3 Binary Tree

image

A Binary Tree is a tree data structure in which each node has at most two children (left and right).

Characteristics of a Binary Tree:


2.2 Introduction to Stack and Queue

2.2.1 Stack

image

A LIFO (Last In First Out) data structure → the last data in is the first one out. Example: a stack of plates in a cafeteria. The last plate placed on top will be the first one taken.

Main operations:

Application in Trees Used in DFS (Depth First Search) or Preorder, Inorder, Postorder traversals. When we enter a child node, the current node is stored on the stack. After finishing with the child, we pop from the stack to continue.

2.2.2 Queue

image

A FIFO (First In First Out) data structure → the first data in is the first one out. Example: a minimarket cashier line, the person who arrives first will be served first.

Main operations:

Application in Trees Used in BFS (Breadth First Search) or Level Order traversal. When visiting a node, its children are added to the queue, then processed one by one in order.


2.3 Traversal in Trees

Traversal is the process of visiting each node in a tree.

2.3.1 Inorder (Left, Root, Right)

// Inorder (Left - Root - Right)
void inorder(Node* root) {
   if (root == nullptr) return;
   inorder(root->left);
   cout << root->data << " ";
   inorder(root->right);
}

2.3.2 Preorder (Root, Left, Right)

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

2.3.3 Postorder (Left, Right, Root)

// Postorder (Left - Right - Root)
void postorder(Node* root) {
   if (root == nullptr) return;
   postorder(root->left);
   postorder(root->right);
   cout << root->data << " ";
}

2.3.4 Level Order

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

2.3.5 Traversal Illustration Example

     50
    /  \
   /    \
  30     70
 / \    / \
20 40  60 80

References


Revision #7
Created 2025-09-06 10:41:02 UTC by YP
Updated 2025-10-30 00:34:05 UTC by RE