Menu
Coddy logo textTech

Binary Tree

Last updated

A binary tree is a hierarchy where each node has at most two children, called the left and right child. The top node is the root, nodes with no children are leaves, and the number of edges from the root to the deepest leaf is the tree's height. Unlike a binary search tree, a plain binary tree has no ordering rule - it's just the shape. Press play above to watch a tree fill level by level, then get walked in-order (left, node, right).

Binary trees underpin many structures - binary search trees, heaps, expression trees, and more. Traversals visit every node in a defined order: in-order, pre-order, and post-order are the three depth-first walks, each useful for different tasks.

Terminology

TermMeaning
RootThe top node, with no parent
LeafA node with no children
HeightLongest root-to-leaf path (in edges)
DepthDistance of a node from the root
CompleteAll levels full except possibly the last, filled left to right

The three depth-first traversals

TraversalOrderCommon use
In-orderLeft, node, rightSorted output of a BST
Pre-orderNode, left, rightCopy / serialize a tree
Post-orderLeft, right, nodeDelete / evaluate a tree

Worked example

In-order traversal of the tree built from [4, 2, 6, 1, 3, 5] (filled level by level):

StepAt nodeAction
14Recurse into left subtree of 4 before visiting it
22Recurse into left subtree of 2 before visiting it
31Leaf, no left child - visit 1, output [1]
42Left done - visit 2, output [1, 2], then recurse right
53Leaf - visit 3, output [1, 2, 3]
64Left subtree done - visit 4, output [1, 2, 3, 4], then recurse right
75Left child of 6, a leaf - visit 5, output [1, 2, 3, 4, 5]
86Left done, no right child - visit 6, output [1, 2, 3, 4, 5, 6]

When to use a binary tree

Use it whenAvoid it when
You need to model inherently hierarchical data (file systems, expression trees, DOM)The data is flat and a list or array would do - a tree only adds overhead
You want ordered operations and can keep it balanced (a BST or self-balancing tree)You need O(1) average lookup by key - a hash table beats any tree
You need in-order, pre-order, or post-order processing of structured dataNodes are inserted in sorted order into an unbalanced BST - it degrades to an O(n) list
Range queries or ordered iteration matter, which hash tables cannot provideMemory is tight - each node carries two child pointers plus the payload

Binary Tree code

A clean, runnable Binary Tree implementation in Python, JavaScript, Java, C++, C. Pick a language, copy the code, or open it pre-loaded in the Coddy Playground.

Binary Tree code in Python

Python
1from collections import deque2
3
4class Node:5    def __init__(self, value):6        self.value = value7        self.left = None8        self.right = None9
10
11def insert(root, value):12    # Level-order insert: fill the first empty child slot found13    if root is None:14        return Node(value)15    queue = deque([root])16    while queue:17        node = queue.popleft()18        if node.left is None:19            node.left = Node(value)20            return root21        queue.append(node.left)22        if node.right is None:23            node.right = Node(value)24            return root25        queue.append(node.right)26
27
28def inorder(node):29    if node is None:30        return []31    return inorder(node.left) + [node.value] + inorder(node.right)32
33
34root = None35for value in [1, 2, 3, 4, 5, 6, 7]:36    root = insert(root, value)37
38print("Root:   ", root.value)39print("Inorder:", inorder(root))
Run this code in the Python Playground

Binary Tree FAQ

What is the difference between a binary tree and a binary search tree?
A binary tree simply restricts each node to at most two children, with no ordering. A binary search tree adds the rule that everything in the left subtree is smaller and everything in the right subtree is larger, which is what makes searching fast.
What is an in-order traversal?
In-order traversal visits the left subtree, then the node, then the right subtree, recursively. For a binary search tree this produces the values in sorted ascending order, which is why it's the most common traversal to demonstrate.
What is a complete binary tree?
A complete binary tree has every level fully filled except possibly the last, which is filled from left to right. This shape lets the tree be stored compactly in an array (no child pointers needed), which is how binary heaps are implemented.
When should I use a binary tree instead of an array or hash table?
Reach for a tree when your data is naturally hierarchical or when you need ordered operations like range queries and sorted iteration, which hash tables cannot give you. If you only need fast key lookup with no ordering, a hash table's O(1) average access beats a tree, and for flat data an array is simpler and more cache-friendly.
What is the difference between the height and the depth of a binary tree?
Depth is measured from the root down to a specific node - the number of edges on the path from the root to that node. Height is measured from a node down to its deepest leaf, so the height of the whole tree is the depth of its deepest node. A single-node tree has height 0, and its only node also has depth 0.
Why does an unbalanced binary tree perform so badly?
Search, insert, and delete in a binary search tree cost O(h) where h is the height. When keys are inserted in sorted order the tree becomes a straight line, so h grows to n and every operation degrades to O(n) - no better than a linked list. Self-balancing trees like AVL or red-black trees keep the height at O(log n) to prevent this.
Coddy programming languages illustration

Master algorithms with Coddy

GET STARTED