Binary tree representation
Beginner · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A binary tree has at most two children per node, usually called left and right. You can store it as little objects pointing to each other, or flatten it into a numbered array where the position tells you the family relations.
Practical use cases
- Web app: Tournament bracket page. A sports site shows a knockout bracket where every match has two feeder matches. Each match is a node with a left and a right feeder, and the final is the root. The page can draw the bracket by walking down from the final through each pair of feeders.
- Web app: Decision tree for a support chatbot. A help bot asks yes or no questions: "Is the item delivered?" leads to two follow-ups. Storing each question as a node with a yes child and a no child makes it easy to add new questions in an admin screen without touching code.
- System: Heaps stored in arrays. Priority queues store their tree in a plain array, where the position of each item tells you where its parent and children are, using simple arithmetic. No pointers are needed, which saves memory and keeps the data tightly packed.
The story: The Tiffin Delivery Chart
Zoya ran a small tiffin service in her mohalla. Every morning her cousin Aarav had to deliver tiffins along a route that split like a tree: from the main road it split into two lanes, and each lane split again. Zoya wanted to hand Aarav the route on paper, but not as a drawing, because the drawing kept getting wet in the rain.
First idea: a card for every junction. Each card says: "Junction number 2. Turn left to card 4, turn right to card 5." If there is no lane in a direction, the card says "nothing". Aarav only ever needs the card he is standing on and the next card number. This is the node-and-pointer way: each node knows its left and right.
Second idea: a single long strip of paper, with boxes numbered 0, 1, 2, 3... The main road goes in box 0, the two lanes in boxes 1 and 2, the next four in boxes 3 to 6, and so on, row by row. To find the lanes after box 4, Aarav does a tiny trick: double the number and add 1 or 2. Missing lanes are left blank.
Zoya smiled: "Cards are flexible when the route is lopsided. The strip is compact when the route is tidy and full. Same tree, two ways to write it down." Aarav took both, just in case.
How to spot this problem, and where you need it
You need to decide how to store a two-way branching structure so it is easy to read, change and walk through, and does not waste memory.
Signs you need it
- Each item has two natural outcomes or two parts, such as yes or no, left or right, winner of match A and match B.
- You are choosing between objects with left and right links, and a flat numbered array for something like a heap.
- The tree is full and tightly packed, so an array has no empty gaps, or it is very uneven, so links work better.
Where to use it in a project
- Brackets, decision flows, expression evaluators and quiz-style question trees.
- Priority queues and heaps, which are stored in arrays for compactness.
The solution
Pick one of two shapes. With linked nodes, each node holds its value plus references to its left and right child, which is flexible and good for uneven trees. With an array, put the root at position 0 and compute children by formula, which is compact and quick for full trees. Choose links when the shape changes a lot, and arrays when it is neat and complete.
Payoff: Before: ad hoc nested arrays that were hard to update. After: a clear node structure where adding a question or match is one small change.
Explain it like I am 8
Imagine a treasure hunt. Way one: every clue card says "go left to card X or right to card Y". Way two: all the clues sit in a numbered row of boxes, and you can calculate where the next clues are from your own box number. Same hunt, written two ways.
How it works, step by step
- Node way: make a small object with
val,leftandright. A missing child isnull. - Keep only the root; every other node is reachable by following left/right pointers down from it.
- Array way: put the root in slot 0, then fill row by row, left to right, leaving empty slots for missing children.
- In the array, for slot
i: left child is in slot2*i + 1, right child in slot2*i + 2. - Pick the node way for general trees (most interview problems) and the array way for full, tidy trees like heaps.
The code in four languages
PHP
<?php
class TreeNode {
public ?TreeNode $left = null;
public ?TreeNode $right = null;
public function __construct(public int $val) {}
}
// The example tree: 1
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
function sampleTree(): TreeNode {
$root = new TreeNode(1);
$root->left = new TreeNode(2);
$root->right = new TreeNode(3);
$root->left->left = new TreeNode(4);
$root->left->right = new TreeNode(5);
$root->right->right = new TreeNode(6);
$root->left->right->left = new TreeNode(7);
return $root;
}
// Way 2: copy the node tree into an array. Slot i has its children in 2i+1 and 2i+2.
function fill(?TreeNode $n, int $i, array &$slots): void {
if ($n === null) return;
$slots[$i] = $n->val;
fill($n->left, 2 * $i + 1, $slots);
fill($n->right, 2 * $i + 2, $slots);
}
function toArray(?TreeNode $root): array {
$slots = [];
fill($root, 0, $slots);
$out = [];
for ($i = 0; $i <= max(array_keys($slots)); $i++) {
$out[] = $slots[$i] ?? null; // gaps become null
}
return $out;
}
$arr = toArray(sampleTree());
echo json_encode($arr) . PHP_EOL; // [1,2,3,4,5,null,6,null,null,7]
$i = 4; // slot 4 holds value 5
echo 'Node ' . $arr[$i] . ' has left=' . ($arr[2 * $i + 1] ?? 'none')
. ' right=' . ($arr[2 * $i + 2] ?? 'none') . PHP_EOL;JavaScript
class TreeNode {
constructor(val) { this.val = val; this.left = null; this.right = null; }
}
// The example tree: 1
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
function sampleTree() {
const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(6);
root.left.right.left = new TreeNode(7);
return root;
}
// Way 2: copy the node tree into an array. Slot i has its children in 2i+1 and 2i+2.
function fill(n, i, slots) {
if (n === null) return;
slots[i] = n.val;
fill(n.left, 2 * i + 1, slots);
fill(n.right, 2 * i + 2, slots);
}
function toArray(root) {
const slots = [];
fill(root, 0, slots);
const out = [];
for (let i = 0; i < slots.length; i++) {
out.push(slots[i] === undefined ? null : slots[i]); // gaps become null
}
return out;
}
const arr = toArray(sampleTree());
console.log(JSON.stringify(arr)); // [1,2,3,4,5,null,6,null,null,7]
const i = 4; // slot 4 holds value 5
const left = arr[2 * i + 1], right = arr[2 * i + 2];
console.log('Node ' + arr[i] + ' has left=' + (left === undefined ? 'none' : left) +
' right=' + (right === undefined ? 'none' : right));Java
import java.util.*;
import java.util.stream.*;
public class Main {
static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
// The example tree: 1
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
static TreeNode sampleTree() {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(6);
root.left.right.left = new TreeNode(7);
return root;
}
// Way 2: copy the node tree into an array. Slot i has its children in 2i+1 and 2i+2.
static void fill(TreeNode n, int i, Map<Integer, Integer> slots) {
if (n == null) return;
slots.put(i, n.val);
fill(n.left, 2 * i + 1, slots);
fill(n.right, 2 * i + 2, slots);
}
static List<Integer> toArray(TreeNode root) {
Map<Integer, Integer> slots = new HashMap<>();
fill(root, 0, slots);
int last = Collections.max(slots.keySet());
List<Integer> out = new ArrayList<>();
for (int i = 0; i <= last; i++) {
out.add(slots.get(i)); // gaps become null
}
return out;
}
// Reads a slot, or says "none" when it is past the end or empty.
static String slot(List<Integer> arr, int i) {
return i < arr.size() && arr.get(i) != null ? String.valueOf(arr.get(i)) : "none";
}
public static void main(String[] args) {
List<Integer> arr = toArray(sampleTree());
System.out.println(arr.stream().map(String::valueOf).collect(Collectors.joining(",", "[", "]")));
// [1,2,3,4,5,null,6,null,null,7]
int i = 4; // slot 4 holds value 5
System.out.println("Node " + arr.get(i) + " has left=" + slot(arr, 2 * i + 1)
+ " right=" + slot(arr, 2 * i + 2));
}
}Go
package main
import (
"encoding/json"
"fmt"
)
type TreeNode struct {
Val int
Left, Right *TreeNode
}
// The example tree: 1
//
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
func sampleTree() *TreeNode {
root := &TreeNode{Val: 1}
root.Left = &TreeNode{Val: 2}
root.Right = &TreeNode{Val: 3}
root.Left.Left = &TreeNode{Val: 4}
root.Left.Right = &TreeNode{Val: 5}
root.Right.Right = &TreeNode{Val: 6}
root.Left.Right.Left = &TreeNode{Val: 7}
return root
}
// Way 2: copy the node tree into an array. Slot i has its children in 2i+1 and 2i+2.
func fill(n *TreeNode, i int, slots map[int]int) {
if n == nil {
return
}
slots[i] = n.Val
fill(n.Left, 2*i+1, slots)
fill(n.Right, 2*i+2, slots)
}
// toArray uses *int so that a gap can be nil (JSON prints it as null).
func toArray(root *TreeNode) []*int {
slots := map[int]int{}
fill(root, 0, slots)
last := 0
for i := range slots {
if i > last {
last = i
}
}
out := make([]*int, last+1)
for i := range out {
if v, ok := slots[i]; ok {
v := v
out[i] = &v
} // else: gap stays nil
}
return out
}
// slot reads a slot, or says "none" when it is past the end or empty.
func slot(arr []*int, i int) string {
if i < len(arr) && arr[i] != nil {
return fmt.Sprint(*arr[i])
}
return "none"
}
func main() {
arr := toArray(sampleTree())
text, _ := json.Marshal(arr)
fmt.Println(string(text)) // [1,2,3,4,5,null,6,null,null,7]
i := 4 // slot 4 holds value 5
fmt.Println("Node", *arr[i], "has left="+slot(arr, 2*i+1), "right="+slot(arr, 2*i+2))
}Time: O(n) · Extra space: O(n). Either layout stores every node once. The array layout wastes slots for each gap, so a long thin tree can need far more slots than nodes.
Watch out for
- Using the array layout for a lopsided tree (like a chain): almost every slot stays empty and memory is wasted.
- Forgetting the root pointer. With node objects, if you lose the root you lose the whole tree.
- Starting the slot count at 1 in one place and 0 in another, so the double-and-add rule points at the wrong children.
Quick check
- In the node way, what does a leaf store for its two child pointers?
- Its parent
- null for both
- Zero for both
- In the array layout (root in slot 0), where is the left child of the node in slot 4?
- Slot 2
- Slot 5
- Slot 8
- Slot 9
- When is the array layout wasteful?
- When values are numbers
- When the tree is full and tidy
- When the tree is long and lopsided