Visualize & Master
Algorithms & Data Structures
Explore classic & modern sorting algorithms, efficient searching techniques, and interactive data structure visualizations — all with real-time step-by-step animation, comparisons, swaps, and Big-O metrics.
About A binary tree is a hierarchical data structure where each node has at most two children, referred to as left and right
A binary tree is a hierarchical data structure where each node has at most two children, referred to as left and right.
It is the foundation for more specialized trees like BSTs, heaps, and expression trees.
How It Works
Each node contains a value and pointers to left and right children.
The topmost node is the root.
Trees are traversed in four primary orders: inorder (left-root-right), preorder (root-left-right), postorder (left-right-root), and level-order (breadth-first, top-to-bottom left-to-right).
Binary trees enable efficient hierarchical representation, with depth O(log n) for balanced trees and O(n) for skewed trees.
Time & Space Complexities
| Operation | Time | Space |
|---|---|---|
| Traversal (inorder) | O(n) | O(h) |
| Traversal (preorder) | O(n) | O(h) |
| Traversal (postorder) | O(n) | O(h) |
| Traversal (level-order) | O(n) | O(n) |
| Height | O(n) | O(h) |
Best Use Cases
- Expression trees for compilers (parsing)
- File system directory structures
- Huffman coding trees (compression)
- Decision trees in machine learning
- XML/HTML DOM representation
- Network routing algorithms (spanning trees)
Worked Example
Traverse the complete tree [42, 17, 88, 33, 65, 21, 90]
Input: root 42, left 17, right 88; 17 → (33, 65); 88 → (21, 90)- 1 Inorder (left, root, right) visits the left subtree first: 33, then 17, then 65.
- 2 Visit the root 42, then descend into the right subtree.
- 3 Right subtree inorder: 21, then 88, then 90.
- 4 Full inorder order: 33, 17, 65, 42, 21, 88, 90.
- 5 Preorder (root, left, right) starts at the root: 42, 17, 33, 65, 88, 21, 90.
- 6 Level-order (BFS) goes top-to-bottom, left-to-right: 42, 17, 88, 33, 65, 21, 90.
Pseudocode
function inorder(node):
if node is null:
return
inorder(node.left)
visit(node)
inorder(node.right) function preorder(node):
if node is null:
return
visit(node)
preorder(node.left)
preorder(node.right) function postorder(node):
if node is null:
return
postorder(node.left)
postorder(node.right)
visit(node) function levelOrder(root):
queue = new Queue()
queue.enqueue(root)
while queue is not empty:
node = queue.dequeue()
visit(node)
if node.left is not null:
queue.enqueue(node.left)
if node.right is not null:
queue.enqueue(node.right) function height(node):
if node is null:
return -1
leftHeight = height(node.left)
rightHeight = height(node.right)
return max(leftHeight, rightHeight) + 1 Inorder Traversal
Select a traversal order to begin.