Tree: Height of a Binary Tree

  • + 0 comments

    Calculates the height of a binary tree recursively. ` public static int recHeight(Node node, int counter) { // Base Case: If the node is null, return the current counter as the height if (node == null) { return counter; }

    // Recursive Case: Calculate the height of the left and right subtrees
    int leftHeight = recHeight(node.left, counter + 1);
    int rightHeight = recHeight(node.right, counter + 1);
    
    // Return the greater of the two heights
    return Math.max(leftHeight, rightHeight);
    

    } `