π³ Understanding Trees in JavaScript with Simple Traversals

When learning Data Structures and Algorithms (DSA), trees are one of the most interesting and useful structures. In this blog, weβll explore what a tree is, how to create one in JavaScript, and how to traverse it using different techniques.
Letβs dive into the basics with some code!
π± What is a Tree?
A tree is a non-linear data structure where each element (called a node) is connected in a hierarchical manner. Each node has:
A piece of data.
A left child.
A right child.
In our example, weβll focus on a binary tree, where each node has at most two children.
π οΈ Step 1: Creating the Tree Structure
class TreeNode {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
Here, TreeNode
is a class to create each node. Every node holds data
, and optionally a left
and right
child node.
π³ Step 2: Building the Tree
const root = new TreeNode('R');
const nodeA = new TreeNode('A');
const nodeB = new TreeNode('B');
const nodeC = new TreeNode('C');
const nodeD = new TreeNode('D');
// Linking the nodes
root.left = nodeA;
root.right = nodeB;
nodeA.left = nodeD;
nodeB.right = nodeC;
This creates the following structure:
R
/ \
A B
/ \
D C
π Step 3: Tree Traversals Explained
Traversal means visiting each node of the tree in a particular order. Weβll cover:
πΉ 1. Pre-Order Traversal (Root β Left β Right)
function preOrderTraversal(treeNode) {
if (treeNode) {
console.log('Node:', treeNode.data);
preOrderTraversal(treeNode.left);
preOrderTraversal(treeNode.right);
}
}
Output: R β A β D β B β C
πΉ 2. Post-Order Traversal (Left β Right β Root)
function postOderTraversal(treeNode) {
if (treeNode) {
postOderTraversal(treeNode.left);
postOderTraversal(treeNode.right);
console.log('Node:', treeNode.data);
}
}
Output: D β A β C β B β R
πΉ 3. In-Order Traversal (Left β Root β Right)
function inOrderTraversal(treeNode) {
if (treeNode) {
inOrderTraversal(treeNode.left);
console.log('Node:', treeNode.data);
inOrderTraversal(treeNode.right);
}
}
Output: D β A β R β B β C
π Final Execution
console.log('π Pre-Order Traversal:');
preOrderTraversal(root);
console.log('π Post-Order Traversal:');
postOderTraversal(root);
console.log('π In-Order Traversal:');
inOrderTraversal(root);
π§ Final Thoughts
Tree structures may seem complex at first, but once you break them down into nodes and connections, they become simple and fun to play with. Using different traversal methods helps you process or search through the tree in various ways β which is powerful in real-world applications like DOM manipulation, game development, and database engines.
Stay curious, and keep coding! π
Subscribe to my newsletter
Read articles from Akash Prajapati directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
