Data Structures · Visualization
Binary Tree: Introduction
Binary Tree
A binary tree is a structure made of nodes, where each node holds a value and points to at most two children, called the 'left' child and the 'right' child. Time: Varies by operation (search/insert/delete are O(h) where h is tree height). Space: O(n).
Big-O: Traversals visit every node exactly once: O(n).
Binary Tree: Introduction
Binary TreeA binary tree is a structure made of nodes, where each node holds a value and points to at most two children, called the 'left' child and the 'right' child. The topmost node is the 'root', and nodes with no children are called 'leaves'. Unlike a linked list's single chain, a tree branches out, which makes it great for representing hierarchical relationships.
How Binary Tree: Introduction Works
- Create a node with a value, a left pointer, and a right pointer (both start as null).
- Designate one node as the root — the entry point to the whole tree.
- Attach child nodes to the left and/or right of any existing node.
- A node with both children null is a leaf; the tree can grow arbitrarily deep.
Binary Tree: Introduction Worked Example
Input: Build a small tree with root 10, left child 5, right child 15
- Create root node(10)
- root.left = node(5)
- root.right = node(15)
Output: 10 / \ 5 15
Press ▶ Run to watch it step by step.
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# A binary tree: each node has 0, 1, or 2 children
# example: introBinary Tree: Introduction Time & Space Complexity
When to Use Binary Tree: Introduction
- Representing hierarchical data like file systems or org charts
- The foundation for binary search trees, heaps, and many other structures
- Expression trees used to evaluate mathematical formulas
- Decision trees in machine learning
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.