A2Z Lesson

Log in
← Back to the A2Z sheet

Step 13 Binary Trees — Theory/Traversals

Introduction

Easy

A binary tree is a hierarchy where each node holds a value and points to at most two children, left and right. Trees model everything from file systems to expression syntax to the recursion structure of divide-and-conquer, and they are the substrate for this whole module: traversals, views, diameters and constructions all assume you are fluent in the vocabulary and the node representation. This lesson builds that foundation before the traversal drills begin.

Vocabulary: the parts of a tree

The root is the single node with no parent. A node's children are its left and right successors; nodes with no children are leaves. The depth of a node is the number of edges from the root to it (root depth 0); the height of a node is the longest downward path to a leaf, and the height of the tree is the height of its root — beware that some sources count nodes instead of edges, shifting every figure by one, so fix the convention before comparing answers.

A subtree is a node together with all its descendants. Ancestors of a node are the nodes on the path from the root down to its parent. Almost every recursive tree algorithm is phrased as: solve for the left subtree, solve for the right subtree, combine at the current node.

Kinds of binary trees

Full: every node has 0 or 2 children. Perfect: full, and all leaves at the same depth — a perfect tree of height h has 2^(h+1) - 1 nodes. Complete: every level except possibly the last is full, and the last level fills left to right — this is the shape heaps use, and it guarantees height O(log n). Balanced: left and right subtree heights differ by at most 1 everywhere (AVL-style), also O(log n) height. Degenerate (skewed): every node has one child — the tree is a linked list in disguise with height O(n).

Height is the master variable: most tree algorithms are O(n) time, but their recursion depth — and BST operation costs — are governed by height, which swings between log n (complete/balanced) and n (skewed) for the same node count.

Representation: nodes, and building from level order

The standard representation mirrors the linked list: a node object with data, left and right references (None for missing children). Problems often give input as a level-order array (breadth-first listing, with nulls for gaps); converting it to nodes uses a queue — pop a node, attach the next two array values as its children, enqueue non-null children.

from collections import deque class TreeNode: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def build_from_level_order(values): if not values or values[0] is None: return None root = TreeNode(values[0]) queue = deque([root]) i = 1 while queue and i < len(values): node = queue.popleft() if i < len(values) and values[i] is not None: node.left = TreeNode(values[i]) queue.append(node.left) i += 1 if i < len(values) and values[i] is not None: node.right = TreeNode(values[i]) queue.append(node.right) i += 1 return root

The traversal family (preview)

Visiting every node exactly once is a traversal. Depth-first traversals are defined by when the root is processed relative to its subtrees: preorder (root, left, right), inorder (left, root, right), postorder (left, right, root). Breadth-first traversal processes level by level using a queue — the same order as the array representation above.

On the tree with root 1, left subtree 2 (children 4, 5) and right child 3: preorder is 1 2 4 5 3; inorder is 4 2 5 1 3; postorder is 4 5 2 3 1; level order is 1 2 3 4 5. The next lessons drill each of these recursively and iteratively; here, just be able to produce all four by hand for a small tree.

Complexity and common mistakes

Any traversal visits each node once: O(n) time. Extra space is O(h) for the recursion stack in DFS (h = height, so O(log n) balanced, O(n) skewed) and O(width) for the BFS queue, which is O(n) for a perfect tree's last level.

Common mistakes: (1) mixing up height conventions (edges vs nodes) and being off by one on depth/height questions; (2) calling a tree complete when it is only full, or vice versa; (3) assuming a binary tree is sorted — the ordering property belongs to the binary SEARCH tree, covered in the next module; (4) forgetting that in level-order input, children of null nodes are not present in the array — the builder above only consumes values for nodes actually dequeued, which is the convention most judges use.

Key points

  • Node = data + left + right; fix your height convention (edges vs nodes) before answering.
  • Perfect and complete trees have height O(log n); a degenerate tree is a list with height O(n) — height drives costs.
  • Complete means last level fills left to right; full means 0 or 2 children everywhere — they are different properties.
  • Traversals: preorder (root-L-R), inorder (L-root-R), postorder (L-R-root), level order (BFS with a queue).
  • Level-order arrays are converted to nodes with a queue; nulls have no children entries in the input.

Suggested questions

Inorder Traversal ↗ First DFS drill: left, root, right — recursively and iteratively.
Preorder Traversal ↗ Root first; also the order used to serialise a tree's shape.
Level Order Traversal ↗ The BFS order — the same sequence the level-order array representation uses.
Maximum Depth in BT ↗ Height from this lesson, computed as 1 + max of the subtree heights.
Postorder Traversal ↗ Root last — the order you need whenever children must be processed before the parent.

Source note: this lesson follows the structure of Striver's public A2Z DSA course (takeUforward). Each problem links to its original platform, and all problems and content belong to their respective owners — STUDY-BUDDY does not claim ownership of the sheet or its problems, and no permission beyond public linking is claimed.