What is a Binary Tree?
Data Structures·6 min·Python code
Binary trees store values in nodes that link to at most two children, called left and right. One root node sits at the top, and every other node descends from it, which models hierarchy and gives ordered search in O(log n) time on balanced trees.
Binary Tree Structure With Roots and Leaves
A binary tree is a set of nodes connected top down. One node is the root, every node stores a value and has up to two links, and either link can be empty. Nodes with no children are leaves.
Think of a family tree, a tournament bracket or the folders on your computer, all structures that branch downward.
Few terms recur more often. Parents sit directly above a node, and subtrees are a node plus everything beneath it. Depth counts edges from the root to a node, and height counts edges on the longest path from a node down to a leaf.
Depth and height decide how long tree operations take.
Four Binary Tree Traversal Orders
Walking the tree comes first. Preorder goes node then left then right. Inorder goes left then node then right. Postorder goes left then right then node.
All three are short recursion built around one base case, where an empty node does nothing. They match Depth-First Search.
Level order, the fourth way, visits the tree row by row using a queue, and it matches Breadth-First Search.
Order choice matters. Inorder on a BST emits sorted values, preorder copies or serialises a tree, postorder frees nodes or evaluates expression trees and level order handles closest first problems.
Binary Search Trees and Balance
Binary search trees add one rule. Every value in a node's left subtree is smaller and every value in its right subtree is larger. That invariant lets you search like binary search does, comparing then going left or right and discarding about half the remaining nodes at every step.
You follow one root to leaf path, so search, insert and delete cost O(h), where h is the height. Balanced trees keep h near log n, which gives O(log n).
Insert values in sorted order and the tree collapses into a chain, so h equals n and every operation costs O(n). Self balancing variants like AVL and red black trees rearrange nodes as you go to guarantee logarithmic height.
Practise on CodeStory's binary tree practice problems.
Binary Tree Code Example in Python
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def inorder(node):
"""Left, node, right: yields BST values in sorted order."""
if node is None:
return []
return inorder(node.left) + [node.value] + inorder(node.right)
def height(node):
"""Edges on the longest root-to-leaf path; empty tree is -1."""
if node is None:
return -1
return 1 + max(height(node.left), height(node.right))
Edit this code in the browser IDE on CodeStory, free on the platform. Open the CodeStory App
Binary Tree Time and Space Complexity
| Time | O(n) for any traversal because it visits every node once. O(h) for BST search, insert and delete, where h is the tree height |
|---|---|
| Space | O(n) to store n nodes. Traversals use O(h) call stack or queue space, from O(log n) when balanced to O(n) when skewed |
Balanced trees have h near log n, so BST operations cost O(log n). Degenerate trees, like those built from sorted inserts, collapse into a chain with h equal to n and O(n) operations.
Watch Binary Trees Step by Step
Seeing the pointer move through every order shows when a node is handled. Follow either of these one step at a time.
When to Use a Binary Tree
- Data is naturally hierarchical, like file systems, org charts, the HTML DOM and decision trees.
- You need ordered keys with quick search, insert and delete together, like the map or set behind many standard libraries (a balanced BST).
- You parse or evaluate structured input, like expression trees and abstract syntax trees.
- You want sorted iteration or range queries for free, since an inorder walk of a BST returns keys in ascending order.
Mistakes to Avoid
- Confusing a binary tree with a binary search tree. Plain binary trees have no ordering guarantee, and only a BST keeps left < node < right, which makes search logarithmic.
- Assuming O(log n) always holds. Unbalanced BSTs, classically from sorted inserts, degrade into linked lists with O(n) operations, so choose a self balancing tree when you need guarantees.
- Forgetting the empty node base case in recursion, or mixing up height and depth. Deep recursion on a skewed tree can overflow the call stack.
Binary Tree FAQs
Is a binary tree hard to learn?
Structure is short, just nodes with up to two children. Real hump is recursion, since most tree operations call themselves on the left and right subtrees. Once traversals click, most tree problems share that recursive shape.
What is the difference between a binary tree and a binary search tree?
Binary trees limit every node to two children, and values can sit in any arrangement. Binary search trees add an ordering rule, smaller values left and larger values right, which enables O(log n) search when the tree is balanced.
What is the time complexity of searching a binary tree?
Plain binary trees with no ordering cost O(n), because you may check every node. Balanced BSTs cost O(log n), since every comparison discards half the remaining nodes. Unbalanced BSTs fall back to O(n) in the worst case.
Which traversal gives sorted order?
Inorder traversal (left, node, right) of a BST visits nodes in ascending order. That follows directly from the BST rule, and it is why inorder is the default for a sorted view of keys.
What is the difference between height and depth in a tree?
Depth counts edges from the root down to a node. Height counts edges on the longest path from a node down to a leaf. Code above gives an empty tree a height of minus 1.
What is a leaf node?
Leaf nodes have no children, so both their left and right links are empty.
How do I practise binary trees on CodeStory?
Watch tree traversals and BST insert and search in the visualisers, then try CodeStory's binary tree practice problems.
Related Guides
Guides are step one. In a CodeStory batch you code the traversals yourself, then explain every recursive call in a scored mock round.
Talk to a Mentor