## [Leetcode]110. Balanced Binary Tree(C++)

### 题目描述

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

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

### 例子

#### 例子 1

Input: `root = [3,9,20,null,null,15,7]` Output: true

#### 例子 2

Input: `root = [1,2,2,3,3,null,null,4,4]` Output: false

#### 例子 3

Input: `root = []` Output: true

### Constraints

• The number of nodes in the tree is in the range `[0, 5000]`.
• `-10^4 <= Node.val <= 10^4`

### 解题思路

• 假如树是空，返回 `0`
• 加入根节点是叶节点，返回 `1`
• 其余情况返回 `max(root->left, root->right) + 1`

``````/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode() : val(0), left(nullptr), right(nullptr) {}
*     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
*     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
* right(right) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
if (!root) return true;
return isBalanced(root->left) && isBalanced(root->right) &&
std::abs(height(root->left) - height(root->right)) <= 1;
}

private:
int height(TreeNode* root) {
if (!root) return 0;
if (!root->left && !root->right) return 1;
return std::max(height(root->left), height(root->right)) + 1;
}
};
``````
• 时间复杂度: O(n)
• 空间复杂度: O(h)

GitHub 代码同步地址： 110.BalancedBinaryTree.cpp