# 110. Balanced Binary Tree

## 1.問題

* 給予一個binary tree, 確定是否屬於高度平衡樹

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LIKXMFgS4Njq3OeAfAj%2F-LIKf2PArbB_c7D3JQ9g%2F2018072607.jpg?alt=media\&token=b78c7617-b1c2-4a3e-bec4-9830bc7560fa)

## 2.想法

* 高度平衡樹的定義
* 利用post-order traversal來比較左右子節點的高度

## 3.程式碼

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if (!root) {
            return true;
        }
        
        return checkHeight(root) != INT_MIN;
    }
private:
    int checkHeight(TreeNode* root) {
        if (!root) {
            return -1;
        }
        int left = checkHeight(root->left);
        if (left == INT_MIN) {
            return INT_MIN;
        }
        
        int right = checkHeight(root->right);
        if (right == INT_MIN) {
            return INT_MIN;
        }
        
        int diff = left - right;
        if (abs(diff) > 1) {
            return INT_MIN;
        } else {
            return max(left, right) + 1;
        }
    }
};
```

## 4.Performance

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LIKXMFgS4Njq3OeAfAj%2F-LIKgZNb7pAGgX6gvFvE%2F2018072608.jpg?alt=media\&token=3ef33ece-e826-4c0f-8332-1bc47e06223c)


---

# Agent Instructions: 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:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/110.-balanced-binary-tree-easy.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
