Sitemap
Emad Mohamed

Emad Mohamed

Software Engineer | PHP | Laravel | Mysql| React | MongoDB | Node | JavaScript |Docker

3 min readMay 28, 2026

--

Tree

Press enter or click to view image in full size

Tree: is a Non-linear Data structure

-Linear vs Non-Linear DS :

Press enter or click to view image in full size

-What is a Tree?

-Tree Definitions :

Press enter or click to view image in full size

-Tree Implementation :

Press enter or click to view image in full size

-Breadth First Traversal : or level by level

-Breadth First Traversal or Breadth First Search BFS

Started from the root. Then print each level

Get Emad Mohamed’s stories in your inbox

Join Medium for free to get updates from this writer.

So output : 0 1 2 3 4 5 6

Breadth First Traversal pseudo code :

Here we will use the queue

Press enter or click to view image in full size

Example :

Press enter or click to view image in full size

Dequeue(0) then push to queue the children of 0 = 1 2 3

Press enter or click to view image in full size

Dequeue(1) then push to queue the children of 1 = 4 5

Press enter or click to view image in full size

In the final, we get :

Press enter or click to view image in full size

JS code that explains BFS :

// 1. Definition of a Tree Node
class Node {
constructor(value) {
this.value = value;
this.left = null; // Left child
this.right = null; // Right child
}
}

// 2. The BFS Function (Using a Queue)
function breadthFirstSearch(root) {
// Base Case: If the tree is empty, just stop
if (root === null) return;

// Step A: Initialize an empty queue and add the root node
const queue = [];
queue.push(root);

// Step B: Loop as long as the queue is not empty
while (queue.length > 0) {
// 1. Remove the front node from the queue to process it
const currentNode = queue.shift();
console.log(`Visited Node: ${currentNode.value}`);

// 2. If the current node has a left child, push it to the queue
if (currentNode.left !== null) {
queue.push(currentNode.left);
}

// 3. If the current node has a right child, push it to the queue
if (currentNode.right !== null) {
queue.push(currentNode.right);
}
}
}

// --- Testing the BFS Algorithm ---

// 3. Building the exact same Binary Tree
// 1
// / \
// 2 3
// / \
// 4 5

const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);

// 4. Run BFS
console.log("--- Starting BFS Traversal ---");
breadthFirstSearch(root);
console.log("------------------------------");

output :

--- Starting BFS Traversal ---
Visited Node: 1
Visited Node: 2
Visited Node: 3
Visited Node: 4
Visited Node: 5
------------------------------

--

--

Emad Mohamed
Emad Mohamed

Written by Emad Mohamed

Software Engineer | PHP | Laravel | Mysql| React | MongoDB | Node | JavaScript |Docker