> For the complete documentation index, see [llms.txt](https://zedive.gitbook.io/project-l/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zedive.gitbook.io/project-l/part-1/basic_data_structure/binary_tree/divide_and_conquer/balanced-binary-tree.md).

# Balanced Binary Tree

## Question ([LC.110](https://leetcode.com/problems/balanced-binary-tree/))

> Given a binary tree, determine if it is height-balanced.

Definition of a height-balanced binary tree: a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

## Example

```
A)  3            B)    3 
   / \                  \
  9  20                 20
    /  \                / \
   15   7              15  7
A: true          B: false
```

## Analysis

Again we try D\&C first. Assign tasks to leftSubtree and rightSubtree to see if they are both balanced then report to the root. If either left or right is not balanced, then the whole tree is not balanced. Or the height difference is greater than 1 then also not balanced.

## Code

Very similar to maxDepth problem. Need to check if leftSub == -1 or rightSub == -1 or height diff > 1

```java
public boolean isBalanced(TreeNode root) {
    return treeDepth(root) >= 0;
}

private int treeDepth(TreeNode root) {
    // base case
    if (root == null)
        return 0;

    // divide
    int leftSubtree = treeDepth(root.left);
    int rightSubtree = treeDepth(root.right);

    // conquer
    if (leftSubtree == -1 || rightSubtree == -1 || Math.abs(leftSubtree - rightSubtree) > 1) {
        return -1;
    } else {
        return 1 + Math.max(leftSubtree, rightSubtree);
    }
}
```

## Analysis #2

From an industry stand point, -1 is very unclear and can be hard to maintain afterward. Java doesn't support returning a tuple (That's why python is op for interview). We need a structure to hold our information. A structure is useful when we need to return 2 or more values.

## Better Code

```java
// we want to return 2 values so we create this structure to simulate a tuple
private class ReturnType {
    boolean isBalanced;
    int depth; // max depth
    ReturnType(boolean isBalanced, int depth) {
        this.isBalanced = isBalanced;
        this.depth = depth;
    }
}

public boolean isBalanced(TreeNode root) {
    return balanceHelper(root).isBalanced;
}

private ReturnType balanceHelper(TreeNode root) {
    // base case
    if (root == null)
        return new ReturnType(true, 0);

    // divide
    ReturnType leftSubtree = balanceHelper(root.left);
    ReturnType rightSubtree = balanceHelper(root.right);

    // conquer
    if (!leftSubtree.isBalanced || !rightSubtree.isBalanced 
                                || Math.abs(leftSubtree.depth - rightSubtree.depth) > 1) {
        return new ReturnType(false, 1 + Math.max(leftSubtree.depth, rightSubtree.depth));
    } else {
        return new ReturnType(true, 1 + Math.max(leftSubtree.depth, rightSubtree.depth));
    }
}
```

## Time Complexity

The time is O(V) because we visit each node exactly once.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://zedive.gitbook.io/project-l/part-1/basic_data_structure/binary_tree/divide_and_conquer/balanced-binary-tree.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
