Binary Tree

Full, perfect, complete trees — traversals, height, diameter, LCA

Introduction

A Binary Tree is a hierarchical data structure in which each node can have at most two children.

These children are commonly referred to as:

  • Left Child
  • Right Child

Binary Trees are one of the most fundamental data structures in Computer Science and serve as the foundation for:

  • Binary Search Trees (BST)
  • AVL Trees
  • Red-Black Trees
  • Heaps
  • Expression Trees
  • Segment Trees
  • Huffman Trees

Real World Analogy

Consider a family tree:

Grandfather
    |
----------------
|              |
Father       Uncle
|
---------
|       |
You   Sibling

Each person can have multiple descendants, creating a tree-like structure.

Similarly, Binary Trees organize data hierarchically.


Binary Tree Terminology

Consider:

          A
         / \
        B   C
       / \   \
      D   E   F

Root Node

The topmost node.

A

Parent Node

A node having child nodes.

Example:

A

is parent of:

B and C

Child Node

Nodes connected below a parent.

Example:

B and C

are children of:

A

Sibling Nodes

Nodes sharing the same parent.

Example:

B and C

Leaf Node

Nodes having no children.

Example:

D, E, F

Internal Node

Nodes having at least one child.

Example:

A, B, C

Edge

Connection between two nodes.

Example:

A → B

Degree of Node

Number of children.

Example:

A = 2
B = 2
F = 0

Depth

Distance from root to a node.

Example:

Depth(A) = 0
Depth(B) = 1
Depth(D) = 2

Height

Longest path from node to leaf.

Example:

Height(D) = 0
Height(B) = 1
Height(A) = 2

Binary Tree Representation

Node Structure

class Node {

    int data;

    Node left;
    Node right;

    Node(int data) {
        this.data = data;
    }
}

Example Binary Tree

          10
         /  \
        5    20
       / \   / \
      2   8 15 25

Properties of Binary Tree


Maximum Nodes at Level L

Formula:

2^L

Example:

Level 0 → 1 Node
Level 1 → 2 Nodes
Level 2 → 4 Nodes
Level 3 → 8 Nodes

Maximum Nodes in Height H

Formula:

2^(H+1) - 1

Example:

Height = 3

Nodes = 15

Minimum Height

For N nodes:

⌈ log₂(N + 1) ⌉ - 1

Types of Binary Trees


1. Full Binary Tree

Every node has either:

  • 0 children
  • 2 children

Example:

        1
       / \
      2   3
     / \
    4   5

Valid Full Binary Tree.


2. Perfect Binary Tree

All internal nodes have 2 children and all leaf nodes are at the same level.

          1
         / \
        2   3
       / \ / \
      4  5 6  7

Properties:

Nodes = 2^(h+1) - 1
Leaves = 2^h

3. Complete Binary Tree

All levels completely filled except possibly the last level.

Last level filled from left to right.

Example:

          1
         / \
        2   3
       / \ /
      4  5 6

4. Balanced Binary Tree

Height difference between left and right subtrees is small.

Example:

        10
       /  \
      5    20

Balanced.


5. Degenerate Binary Tree

Each parent has only one child.

Example:

10
 \
 20
  \
   30
    \
     40

Behaves like a linked list.


Tree Traversal

Traversal means visiting every node exactly once.

There are two major categories:

  1. Depth First Traversal (DFS)
  2. Breadth First Traversal (BFS)

Depth First Traversal (DFS)


1. Preorder Traversal

Order:

Root → Left → Right

Example Tree:

          A
         / \
        B   C
       / \
      D   E

Traversal:

A B D E C

Java Implementation

public void preorder(Node root) {

    if(root == null)
        return;

    System.out.print(root.data + " ");

    preorder(root.left);
    preorder(root.right);
}

2. Inorder Traversal

Order:

Left → Root → Right

Example:

D B E A C

Java Implementation

public void inorder(Node root) {

    if(root == null)
        return;

    inorder(root.left);

    System.out.print(root.data + " ");

    inorder(root.right);
}

3. Postorder Traversal

Order:

Left → Right → Root

Example:

D E B C A

Java Implementation

public void postorder(Node root) {

    if(root == null)
        return;

    postorder(root.left);
    postorder(root.right);

    System.out.print(root.data + " ");
}

Breadth First Traversal (Level Order)

Visits nodes level by level.

Example:

A B C D E

Java Implementation

public void levelOrder(Node root) {

    if(root == null)
        return;

    Queue<Node> queue = new LinkedList<>();

    queue.offer(root);

    while(!queue.isEmpty()) {

        Node current = queue.poll();

        System.out.print(current.data + " ");

        if(current.left != null)
            queue.offer(current.left);

        if(current.right != null)
            queue.offer(current.right);
    }
}

Binary Tree Operations


Insertion

Insert a new node into the tree.

Commonly performed level-wise.

Time Complexity:

O(n)

Find whether a value exists.

Example:

Find 15

Traverse until found.

Time Complexity:

O(n)

Deletion

Steps:

  1. Find node
  2. Replace with deepest node
  3. Delete deepest node

Time Complexity:

O(n)

Height of Binary Tree

Height = Longest path from root to leaf.


Recursive Formula

Height(root)

=
1 + max(
    height(left),
    height(right)
)

Java Implementation

public int height(Node root) {

    if(root == null)
        return -1;

    return 1 + Math.max(
            height(root.left),
            height(root.right)
    );
}

Count Total Nodes

public int count(Node root) {

    if(root == null)
        return 0;

    return 1
            + count(root.left)
            + count(root.right);
}

Time Complexity:

O(n)

Count Leaf Nodes

public int countLeaves(Node root) {

    if(root == null)
        return 0;

    if(root.left == null &&
       root.right == null)
        return 1;

    return countLeaves(root.left)
           +
           countLeaves(root.right);
}

Mirror Binary Tree

Original:

      1
     / \
    2   3

Mirror:

      1
     / \
    3   2

Java Implementation

public Node mirror(Node root) {

    if(root == null)
        return null;

    Node temp = root.left;

    root.left = root.right;
    root.right = temp;

    mirror(root.left);
    mirror(root.right);

    return root;
}

Diameter of Binary Tree

Diameter = Longest path between two nodes.

Example:

      1
     / \
    2   3
   /
  4

Diameter:

4 → 2 → 1 → 3

Length:

3 edges

Binary Tree Complexity Analysis

OperationComplexity
SearchO(n)
InsertO(n)
DeleteO(n)
TraversalO(n)
Height CalculationO(n)

Applications of Binary Trees


Expression Trees

Used by compilers.

Example:

      +
     / \
    A   B

Represents:

A + B

File Systems

Directory structure.

Root
|
+---Documents
|
+---Pictures

Database Indexing

Balanced trees improve search performance.

Examples:

  • AVL Tree
  • B Tree
  • B+ Tree

Decision Trees

Used in Machine Learning.


Huffman Coding

Used in data compression.


Game Trees

Used in Chess and AI systems.


Common Interview Questions

Easy

  1. What is a Binary Tree?
  2. Difference between Tree and Binary Tree?
  3. What is Height?
  4. What is Depth?

Medium

  1. Implement Tree Traversals.
  2. Find Height.
  3. Count Nodes.
  4. Count Leaf Nodes.
  5. Mirror Binary Tree.

Hard

  1. Diameter of Binary Tree.
  2. Lowest Common Ancestor.
  3. Vertical Order Traversal.
  4. Boundary Traversal.
  5. Serialize and Deserialize Binary Tree.

Binary Tree vs Binary Search Tree

FeatureBinary TreeBST
Ordering RuleNoYes
SearchO(n)O(log n) Average
Inorder TraversalRandomSorted
BalancingNot RequiredDepends

Summary

A Binary Tree is a hierarchical data structure where each node has at most two children.

Important Concepts

  • Root
  • Parent
  • Child
  • Leaf
  • Height
  • Depth
  • Degree

Traversals

DFS

  • Preorder
  • Inorder
  • Postorder

BFS

  • Level Order

Complexity

OperationComplexity
SearchO(n)
InsertO(n)
DeleteO(n)
TraversalO(n)

Binary Trees form the foundation of many advanced tree structures such as BST, AVL Trees, Heaps, Segment Trees, and Red-Black Trees, making them one of the most important topics in Data Structures and Algorithms.