Skip to content

TreeDepthCalculator

Utility class to calculate the height (depth) of a binary tree. The height of a tree is defined as:

  • The number of edges in the longest path from root to a leaf

Note:

  • Height of an empty tree = -1
  • Height of a single node tree = 0 Time Complexity: O(n) Space Complexity: O(h) (recursion stack)

calculateHeight

Computes the height of a binary tree using recursion. The function calculates height by: 1. Recursively finding height of left subtree 2. Recursively finding height of right subtree 3. Returning max(left, right) + 1

int calculateHeight(Node root) {
    if (root == null)
        return -1;
    int lHeight = calculateHeight(root.left);
    int rHeight = calculateHeight(root.right);
    return Math.max(lHeight, rHeight) + 1;
}

Usage

    Node root = new Node(12);
    root.left = new Node(8);
    root.right = new Node(18);
    root.left.left = new Node(5);
    root.left.right = new Node(11);
    System.out.println(calculateHeight(root));

Node

Represents a node in a binary tree. Each node contains:

  • Data (integer value)
  • Reference to left child
  • Reference to right child
class Node {

    int data;

    Node left;

    Node right;

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