Binary tree

The notes

Terminology

Each node has at most 2 children.

  • Root node (at level 0)
  • Edge
  • Path
  • Parent, child and sibling nodes
  • Internal node
  • Leaf node
  • Left subtree and right subtree
  • Depth of a node, levels and height

Common types of binary trees

  • 1. Full binary tree: every node has 0 or 2 children
  • 2. Complete binary tree: all levels are fully filled except possibly the last, with nodes as far left as possible
  • 3. Perfect binary tree: all internal nodes have 2 children and all leaves are at the same level
  • 4. Skewed tree: nodes lean predominantly left or right (left-skewed or right-skewed)

Binary tree traversals

Methods to visit all nodes.

Depth-first search (DFS): pre-order (NLR)

  • 1. Visit node (N)
  • 2. Traverse left (L)
  • 3. Traverse right (R)
  • Output: A, B, D, E, C

Depth-first search (DFS): in-order (LNR)

  • 1. Traverse left (L)
  • 2. Visit node (N)
  • 3. Traverse right (R)
  • Output: D, B, E, A, C
  • Used for sorting in a BST

Depth-first search (DFS): post-order (LRN)

  • 1. Traverse left (L)
  • 2. Traverse right (R)
  • 3. Visit node (N)
  • Output: D, E, B, C, A

Breadth-first search (BFS): level-order

  • Visit nodes level by level, left to right
  • Order: level 0, then level 1, then level 2
  • Output: A, B, C, D, E, F, G

Data structures deck

  1. 1. Linear vs non-linear
  2. 2. Arrays
  3. 3. Hashmaps
  4. 4. Stacks
  5. 5. Queue
  6. 6. Linked list
  7. 7. Binary tree
  8. 8. BST
  9. 9. Graphs
  10. 10. Heaps

Watch the lesson

Data structures, Lesson 14, from 1:07: What is a Binary Tree?