Skip to main content
Data Structures
CHAPTER 19 Beginner

Binary Trees

Updated: May 17, 2026
15 min read

# CHAPTER 19

Binary Trees

1. Introduction

In Chapter 18, we explored generic Trees where a Parent could have an infinite number of children. These generic structures are incredibly difficult to traverse mathematically because you never know how wide a branch will be. To unlock high-performance algorithmic speeds, computer scientists imposed a strict, draconian law upon the Tree architecture: A Parent Node may have a maximum of TWO children. This structure is the Binary Tree, and it is the absolute focal point of 80% of all FAANG coding interviews.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define the structural laws of a Binary Tree.
  • Implement a Binary Node in code (left and right pointers).
  • Execute Depth-First Search (DFS) traversals: Pre-order, In-order, Post-order.
  • Execute Breadth-First Search (BFS) Level-order traversal.
  • Understand the immense power of Recursion in Tree logic.

3. The Architecture: Left and Right

Because a Binary Node is mathematically restricted to a maximum of 2 children, we do not need to use an Array to hold the pointers. We simply declare two explicit variables: left and right.
java
1234567891011
// Java Example: The anatomy of a Binary Node
class Node {
    int data;
    Node left;  // Pointer to the Left Child
    Node right; // Pointer to the Right Child

    public Node(int item) {
        data = item;
        left = right = null; // Children are initially empty
    }
}

Visualizing a Binary Tree:

text
12345
        [ 1 ]
       /     \
    [ 2 ]   [ 3 ]
   /    \
[ 4 ]  [ 5 ]

4. Tree Traversal Algorithms

How do you print every number in a Tree? In an Array, you just run a for loop from 0 to N. In a Tree, there is no straight line! You must navigate the complex branches using specific pathing algorithms.

There are two massive families of Traversal Algorithms:

  1. 1. Depth-First Search (DFS): Dive as deep as physically possible down a single branch until you hit a Leaf, then backtrack. (Uses Recursion/Stacks).
  1. 2. Breadth-First Search (BFS): Read the tree horizontally, level by level, from top to bottom. (Uses Queues).

5. Depth-First Search (DFS) Traversals

DFS is implemented utilizing the majestic power of Recursion. There are three variations of DFS, defined entirely by *when* you choose to print the data of the current Node.

#### 5.1 Pre-order Traversal (Node, Left, Right)

  1. 1. Print the current Node's data.
  1. 2. Recursively travel down the Left branch.
  1. 3. Recursively travel down the Right branch.
*Output of diagram above: 1, 2, 4, 5, 3* (Used heavily to create a perfect "copy" of a Tree).

#### 5.2 In-order Traversal (Left, Node, Right)

  1. 1. Recursively dive down the Left branch to the absolute bottom.
  1. 2. Print the current Node's data.
  1. 3. Recursively travel down the Right branch.
*Output of diagram above: 4, 2, 5, 1, 3* (In Chapter 20, we will learn this magically prints data in perfect numerical/alphabetical order!).

#### 5.3 Post-order Traversal (Left, Right, Node)

  1. 1. Recursively dive down the Left branch.
  1. 2. Recursively dive down the Right branch.
  1. 3. Print the current Node's data.
*Output of diagram above: 4, 5, 2, 3, 1* (Used heavily by Operating Systems to permanently delete a Tree from RAM, because it safely deletes the children before deleting the parent).

python
12345678
# Python Example: The sheer elegance of DFS Recursive Traversals
def inorder_traversal(node):
    if node is None:
        return # Base Case: We fell off the tree!
        
    inorder_traversal(node.left)   # 1. Dive Left
    print(node.data, end=" ")      # 2. Print Center
    inorder_traversal(node.right)  # 3. Dive Right

6. Breadth-First Search (BFS) / Level-Order Traversal

If we want to read the Tree horizontally (Level 0, then Level 1, then Level 2), Recursion cannot help us! We must use an Iterative while loop paired with a Queue Data Structure (FIFO).

*Output of diagram above: 1, 2, 3, 4, 5*

cpp
1234567891011121314151617181920212223
// C++ Example: BFS Level-Order Traversal using a Queue
#include <iostream>
#include <queue>
using namespace std;

void levelOrderTraversal(Node* root) {
    if (root == NULL) return;

    queue<Node*> q;
    q.push(root); // Enqueue the top of the tree!

    while (!q.empty()) {
        Node* current = q.front();
        cout << current->data << " ";
        q.pop(); // Dequeue the node

        // If the left child exists, throw it in the back of the queue!
        if (current->left != NULL) q.push(current->left);
        
        // If the right child exists, throw it in the back of the queue!
        if (current->right != NULL) q.push(current->right);
    }
}

7. Complexity Analysis of Traversals

Because every single Traversal algorithm (DFS and BFS) physically visits every single Node exactly one time, the execution speed is mathematically identical.
  • Time Complexity: O(n) Linear Time.
  • Space Complexity (DFS): O(h) where h is the height of the tree (due to the OS Call Stack recursion depth).
  • Space Complexity (BFS): O(w) where w is the maximum width of the tree (due to the size of the Queue).

8. Types of Binary Trees

Interviewers love asking you to classify the architecture of a specific tree.
  • Full Binary Tree: Every single node has either 0 children, or exactly 2 children. (No nodes with just 1 child).
  • Complete Binary Tree: Every level is completely filled with nodes, except possibly the deepest level, which must be filled from left to right without gaps.
  • Perfect Binary Tree: The absolute ultimate symmetry. Every internal node has 2 children, and every single leaf is on the exact same depth level.

9. Common Mistakes

  • Null Pointer Exceptions during Recursion: A junior developer will often write print(node.left.data) without checking if node.left actually exists. Always define the base case if (node == null) return; at the absolute top of the recursive function to securely handle falling off the tree.

10. Best Practices

  • Mental Modeling: When trying to understand a Recursive Tree algorithm, do not try to trace the entire tree in your head. You will get a headache. Only look at a microscopic Subtree consisting of exactly 3 nodes (A Parent, a Left Child, a Right Child). If the recursive algorithm works on those 3 nodes, it mathematically guarantees it will work on 3 billion nodes.

11. Exercises

  1. 1. Draw a generic, unbalanced Binary Tree with 6 nodes. Manually write out the sequence of numbers it would produce under Pre-order, In-order, and Post-order traversal.
  1. 2. In the BFS Queue algorithm, why does it mathematically guarantee that Level 2 is processed before Level 3?

12. MCQs with Answers

Question 1

What is the defining, uncompromising architectural constraint that converts a generic Tree into a Binary Tree?

Question 2

Because of this architectural constraint, how is a Binary Node typically implemented in Object-Oriented code?

Question 3

Which major family of Tree Traversal Algorithms prioritizes diving vertically down a single branch to the absolute deepest Leaf before backtracking?

Question 4

In an In-order DFS Traversal algorithm, what is the exact execution sequence of operations?

Question 5

If an Operating System needs to aggressively delete an entire Binary Tree from RAM without causing Memory Leaks, which DFS traversal method MUST it use?

Question 6

Breadth-First Search (BFS) reads the Tree horizontally, level-by-level. What Abstract Data Type is fundamentally required to successfully write an iterative BFS algorithm?

Question 7

What is the Time Complexity for printing the entire contents of a Binary Tree containing N nodes using an In-order traversal?

Question 8

What defines a "Perfect Binary Tree"?

Question 9

When a software engineer writes a 4-line recursive DFS algorithm, where is the physical memory for the traversal tracking actually stored?

Question 10

What is the output of a Pre-order traversal on a microscopic tree where Root=A, Left=B, Right=C?

13. Interview Preparation

Top Interview Questions:
  • *Algorithmic Coding:* "Write a recursive algorithm to calculate the absolute Maximum Height (Depth) of a Binary Tree." *(Answer: return 1 + max(getHeight(node.left), getHeight(node.right))). This 1-line code blows interviewers' minds!*
  • *Algorithmic Coding:* "Invert a Binary Tree. (Mirror it so all left nodes become right nodes, and vice versa)." *(Answer: The famous question that failed the creator of Homebrew at Google! Use Post-Order traversal. Dive to the bottom, and swap node.left and node.right on the way back up!)*

Common Pitfalls:

  • In iterative BFS implementation, attempting to write queue.add(current.left) without wrapping it in an if (current.left != null) check. This will push NULL into your queue, crashing the loop on the next iteration.

14. FAQs

Q: Why do we need three different ways (Pre, In, Post) to do DFS? A: Because Trees hold different types of data! If the Tree represents a mathematical equation (3 + 4), Pre-order generates Polish Notation + 3 4. Post-order generates Reverse Polish Notation 3 4 +. In-order prints exactly what humans read 3 + 4!

15. Summary

The Binary Tree brings absolute mathematical order to hierarchical structures. By limiting branching to explicit Left and Right pointers, we unlocked the immense power of Recursive DFS traversing and Queue-based BFS horizontal scanning. These algorithms are the literal DNA of high-end software engineering.

16. Next Chapter Recommendation

Binary Trees are neat, but searching them still takes O(n) time because the numbers are scattered randomly. What if we impose ONE MORE mathematical law: "All smaller numbers MUST go left, and all larger numbers MUST go right"? In Chapter 20: Binary Search Trees (BST), we will achieve terrifying, database-level search speeds.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·