Skip to content

Tree Representation


The most natural way — each node holds data and pointers to children.

class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
// Building a tree manually:
const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
[1]
/ \
[2] [3]
/
[4]
ProsCons
Dynamic size, easy insertion/deletionExtra memory for pointers (~2 per node)
Natural for recursion
Sparse trees are memory efficient

A Complete Binary Tree can be stored in an array using index math:

[1] Index: 0
/ \
[2] [3] Index: 1, 2
/ \ / \
[4] [5][6] [7] Index: 3, 4, 5, 6
Array: [1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5, 6]

Index Formulas (0-indexed):

RelationFormula
Left child2 * i + 1
Right child2 * i + 2
ParentMath.floor((i-1)/2)
ProsCons
No pointer overheadWorks best for complete/perfect trees
Cache-friendlyWastes space for sparse trees
Simple math-based navigationInsertion/deletion shift elements

ScenarioRecommended
General tree problemsPointer-based
Heap implementationArray-based
Segment TreeArray-based
Memory-constrainedArray-based
Dynamic insertions/deletionsPointer-based