00:00

Binary Tree in Data Structure

Last updated:

A binary tree is the most widely used kind of tree: every node has at most two children. Binary search trees, heaps, AVL trees, red-black trees and expression trees are all binary trees with extra rules. This tutorial covers the definition, the vocabulary, the main kinds of binary tree, the basic operations with Java programs, and their cost.

What is a Binary Tree?

A binary tree is a tree in which each node has at most two children, called the left child and the right child. The topmost node is the root, and nodes without children are leaves. A plain binary tree places no rule on where values go; that is what distinguishes it from a binary search tree.

Binary trees are used to represent hierarchical data, to evaluate arithmetic expressions (expression trees), to build heaps for priority queues, and as the basis of search trees.

Binary tree with root 50 in which every node has at most two children

Every node of a binary tree has three parts:

  1. Data
  2. Reference to the left child (null if there is none)
  3. Reference to the right child (null if there is none)

Binary Tree Terminologies

  • Node: an element of the tree, holding a value and references to its children.
  • Edge: the link between a parent and a child. A tree with n nodes has n − 1 edges.
  • Root Node: the topmost node; the only node without a parent. A tree has exactly one root.
  • Parent Node: a node that has at least one child.
  • Child Node: a node directly below another node; in a binary tree it is either a left or a right child.
  • Leaf Node: a node with no children.
  • Internal Node: a node with at least one child (also called a non-terminal node).
  • Degree of a Node: the number of children of the node; in a binary tree it is 0, 1 or 2.
  • Depth of a Node: the number of edges from the root to the node; the root has depth 0.
  • Height of a Node: the number of edges on the longest path from the node down to a leaf; every leaf has height 0.
  • Level of a Node: the root is at level 0, its children at level 1, and so on (equal to the depth).
  • Path: the sequence of nodes and edges from one node to another; its length is usually counted in edges.
  • Subtree: a node together with all of its descendants. Each child of a node is the root of a subtree.

Binary Tree Representation

A binary tree node in Java

Node.java
class Node {
  int data;
  Node left, right;

  // constructor
  public Node(int item) {
      data = item;
      left = right = null;
  }
}

Types of Binary Tree

Binary trees are classified by their shape:

  1. Full Binary Tree: every node has either 0 or 2 children.
  2. Perfect Binary Tree: every internal node has 2 children and all leaves are on the same level.
  3. Complete Binary Tree: every level is completely filled except possibly the last, which is filled from the left. Binary heaps are complete trees.
  4. Degenerate (Pathological) Tree: every internal node has exactly one child, so the tree behaves like a linked list.
  5. Skewed Binary Tree: a degenerate tree whose nodes all lean the same way (all left children or all right children).
  6. Balanced Binary Tree: the heights of the left and right subtrees of every node differ by a small, bounded amount, so the height stays O(log n).

Several important structures are binary trees with extra rules:

  1. Binary Search Tree: left subtree values are smaller and right subtree values larger than the node.
  2. AVL Tree: a self-balancing BST in which subtree heights differ by at most 1.
  3. Red-Black Tree: a self-balancing BST that uses node colours to stay balanced.
  4. Binary Heap: a complete binary tree in which every parent is smaller (min-heap) or larger (max-heap) than its children.

B-trees and B+ trees are not binary trees: their nodes can have many children. They are covered in their own tutorials.

Operations On Binary Tree in Data Structure

The basic operations on a binary tree are:

  1. Insertion
  2. Deletion
  3. Searching
  4. Traversing

1. Insertion

A plain binary tree has no ordering rule, so a new node can go anywhere. A common convention keeps the tree as compact as possible: walk the tree level by level with a queue (breadth-first) and attach the new node at the first free child position found. This takes O(n) time in the worst case.

Example of Insert Operation in Binary Tree

BinaryTreeInsertOperation.java
import java.util.LinkedList;
import java.util.Queue;

class Node {
  int data;
  Node left, right;

  Node(int d) {
    data = d;
    left = right = null;
  }
}

class BinaryTreeInsertOperation {
  // Method to insert a new node in the binary tree
  static Node insertNode(Node root, int key) {
    if (root == null)
      return new Node(key);

    // Create a queue for level order traversal
    Queue<Node> queue = new LinkedList<>();
    queue.add(root);

    while (!queue.isEmpty()) {
      Node temp = queue.poll();

      // If left child is empty, insert the new node here
      if (temp.left == null) {
        temp.left = new Node(key);
        break;
      } else {
        queue.add(temp.left);
      }

      // If right child is empty, insert the new node here
      if (temp.right == null) {
        temp.right = new Node(key);
        break;
      } else {
        queue.add(temp.right);
      }
    }
    return root;
  }

  // Method to inorder traversal
  static void inorderTraversal(Node root) {
    if (root == null)
      return;
    inorderTraversal(root.left);
    System.out.print(root.data + " ");
    inorderTraversal(root.right);
  }

  public static void main(String[] args) {
    Node root = new Node(70);
    root.left = new Node(30);
    root.right = new Node(40);
    root.left.left = new Node(50);

    System.out.print("Binary tree before insertion: ");
    inorderTraversal(root);
    System.out.println();

    int new_element = 60;
    root = insertNode(root, new_element);

    System.out.print("Binary tree after insertion: ");
    inorderTraversal(root);
    System.out.println();
  }
}
Output
Binary tree before insertion: 50 30 70 40
Binary tree after insertion: 50 30 60 70 40

The tree before insertion is 70 (root) with children 30 and 40, and 50 as the left child of 30. The first free position in level order is the right child of 30, so 60 goes there; the inorder traversal shows it between 30 and 70.

2. Deletion

To delete a value without leaving a gap, the usual approach is: find the node that holds the value, copy the value of the deepest, rightmost node into it, and then remove that deepest node (which is always a leaf). Both searches are breadth-first, so deletion takes O(n) time.

Example of Delete Operation in Binary Tree

BinaryTreeDeleteOperation.java
import java.util.LinkedList;
import java.util.Queue;

class Node {
  int data;
  Node left, right;

  Node(int key) {
    data = key;
    left = right = null;
  }
}

class BinaryTreeDeleteOperation {
  // Method to delete a node from the binary tree
  static Node deleteNode(Node root, int val) {
    if (root == null)
      return null;

    // Use a queue to perform BFS
    Queue<Node> queue = new LinkedList<>();
    queue.add(root);
    Node target = null;

    // Find the target node
    while (!queue.isEmpty()) {
      Node currentNode = queue.poll();

      if (currentNode.data == val) {
        target = currentNode;
        break;
      }
      if (currentNode.left != null)
        queue.add(currentNode.left);
      if (currentNode.right != null)
        queue.add(currentNode.right);
    }
    if (target == null)
      return root;

    // Find the deepest rightmost node and its parent
    Node lastNode = null;
    Node lastParent = null;
    Queue<Node> queue1 = new LinkedList<>();
    Queue<Node> parentQueue = new LinkedList<>();
    queue1.add(root);
    parentQueue.add(null);

    while (!queue1.isEmpty()) {
      Node currentNode = queue1.poll();
      Node parentNode = parentQueue.poll();

      lastNode = currentNode;
      lastParent = parentNode;

      if (currentNode.left != null) {
        queue1.add(currentNode.left);
        parentQueue.add(currentNode);
      }
      if (currentNode.right != null) {
        queue1.add(currentNode.right);
        parentQueue.add(currentNode);
      }
    }

    // Replace target's value with the last node's value
    target.data = lastNode.data;

    // Removing the last node
    if (lastParent != null) {
      if (lastParent.left == lastNode)
        lastParent.left = null;
      else
        lastParent.right = null;
    } else {
      return null;
    }
    return root;
  }

  // In-order traversal
  static void inorderTraversal(Node root) {
    if (root == null)
      return;
    inorderTraversal(root.left);
    System.out.print(root.data + " ");
    inorderTraversal(root.right);
  }

  public static void main(String[] args) {
    Node root = new Node(20);
    root.left = new Node(30);
    root.right = new Node(40);
    root.left.left = new Node(50);
    root.left.right = new Node(60);

    System.out.print("Binary Tree before deletion operation: ");
    inorderTraversal(root);
    System.out.println();

    int deleteNode = 30;
    root = deleteNode(root, deleteNode);

    System.out.print("Binary Tree after deleting " + deleteNode + " : ");
    inorderTraversal(root);
    System.out.println();
  }
}
Output
Binary Tree before deletion operation: 50 30 60 20 40
Binary Tree after deleting 30 : 50 60 20 40

Deleting 30: the deepest, rightmost node is 60, so 30 is replaced by 60 and the old leaf 60 is removed.

3. Searching

Because a plain binary tree has no ordering rule, a search may have to look at every node. The program below uses a depth-first search: check the current node, then search the left and right subtrees. It takes O(n) time.

Example of Search Operation in Binary Tree

BinaryTreeSearchOperation.java
class Node {
  int data;
  Node left, right;

  Node(int key) {
    data = key;
    left = right = null;
  }
}

public class BinaryTreeSearchOperation {
  // Using DFS traversal method, searching a node in a binary tree
  static boolean searchDFS(Node root, int value) {
    // Return false if the tree is empty or we've reached a leaf node
    if (root == null)
      return false;

    // Return true if searching data is available in the binary tree
    if (root.data == value)
      return true;

    // Recursively search in the left and right subtrees
    boolean left_res = searchDFS(root.left, value);
    boolean right_res = searchDFS(root.right, value);

    return left_res || right_res;
  }

  public static void main(String[] args) {
    Node root = new Node(20);
    root.left = new Node(30);
    root.right = new Node(40);
    root.left.left = new Node(50);
    root.left.right = new Node(60);

    int search_data = 40; // Available in the Binary Tree
    if (searchDFS(root, search_data))
      System.out.println(search_data + " is found in the binary tree");
    else
      System.out.println(search_data + " is not found in the binary tree");

    search_data = 70; // Not Available in the Binary Tree
    if (searchDFS(root, search_data))
      System.out.println(search_data + " is found in the binary tree");
    else
      System.out.println(search_data + " is not found in the binary tree");
  }
}
Output
40 is found in the binary tree
70 is not found in the binary tree

4. Traversing

A traversal visits every node exactly once. Traversals fall into two families:

  1. Depth-first (DFS): inorder, preorder and postorder go as deep as possible along a branch before backtracking (recursion or a stack).
  2. Breadth-first (BFS): level order visits the tree level by level, left to right, using a queue.

Example of Traversal Operations in Binary Tree

BinaryTreeTraversal.java
import java.util.LinkedList;
import java.util.Queue;

class Node {
  int data;
  Node left, right;

  Node(int key) {
    data = key;
    left = right = null;
  }
}

class BinaryTreeTraversal {
  // In-order DFS Traversal (Left -> Root -> Right)
  static void inOrderDFS(Node node) {
    if (node == null)
      return;
    inOrderDFS(node.left);
    System.out.print(node.data + " ");
    inOrderDFS(node.right);
  }

  // Pre-order DFS Traversal (Root -> Left -> Right)
  static void preOrderDFS(Node node) {
    if (node == null)
      return;
    System.out.print(node.data + " ");
    preOrderDFS(node.left);
    preOrderDFS(node.right);
  }

  // Post-order DFS Traversal (Left -> Right -> Root)
  static void postOrderDFS(Node node) {
    if (node == null)
      return;
    postOrderDFS(node.left);
    postOrderDFS(node.right);
    System.out.print(node.data + " ");
  }

  // BFS: Level order traversal
  static void levelOrderBFS(Node root) {
    if (root == null)
      return;
    Queue<Node> queue = new LinkedList<>();
    queue.add(root);

    while (!queue.isEmpty()) {
      Node node = queue.poll();
      System.out.print(node.data + " ");
      if (node.left != null)
        queue.add(node.left);
      if (node.right != null)
        queue.add(node.right);
    }
  }

  public static void main(String[] args) {
    Node root = new Node(20);
    root.left = new Node(30);
    root.right = new Node(40);
    root.left.left = new Node(50);

    System.out.print("In-order DFS Traversal: ");
    inOrderDFS(root);
    System.out.print("\nPre-order DFS Traversal: ");
    preOrderDFS(root);
    System.out.print("\nPost-order DFS Traversal: ");
    postOrderDFS(root);
    System.out.print("\nLevel order BFS Traversal: ");
    levelOrderBFS(root);
  }
}
Output
In-order DFS Traversal: 50 30 20 40
Pre-order DFS Traversal: 20 30 50 40
Post-order DFS Traversal: 50 30 40 20
Level order BFS Traversal: 20 30 40 50

Time and Space Complexity of Binary Tree

OperationsTime ComplexityExtra Space
Insertion (level order)O(n)O(n) for the queue
Deletion (level order)O(n)O(n) for the queue
Searching (DFS)O(n)O(h) for the recursion
Traversal
(In-order, Pre-order, Post-order)
O(n)O(h)
Traversal (level order)O(n)O(w), the widest level

Here, n is the number of nodes, h the height of the tree (between log n and n), and w the largest number of nodes on one level. Searching becomes O(log n) only in a balanced binary search tree, not in a plain binary tree.

Advantages of Binary Trees

  • Natural model of hierarchy: expressions, decisions and nested data map directly onto a binary tree.
  • Foundation for fast structures: adding an ordering or shape rule gives binary search trees (O(log n) search when balanced) and heaps (O(log n) priority-queue operations).
  • Dynamic size: nodes are created as needed; no capacity has to be fixed in advance.
  • Simple recursive algorithms: each subtree is itself a binary tree, so height, size, mirror and traversal methods are a few lines of recursion.
  • Compact array form for complete trees: a heap can be stored in an array with no references at all.

Disadvantages of Binary Trees

  • Slow search without an ordering rule: finding a value in a plain binary tree is O(n).
  • Can degenerate: an unbalanced tree can become a chain of height n, losing the benefit of the tree shape.
  • Memory overhead: each node stores two references in addition to its data.
  • Balancing is complex: keeping a tree balanced requires extra rules and rotations (AVL, red-black).
  • At most two children: data with a high branching factor, such as disk-based indexes, is better served by multi-way trees like B-trees.