题目链接:https://leetcode-cn.com/problems/balanced-binary-tree/
给定一个二叉树,判断它是否是高度平衡的二叉树。
1 /**
2 * Definition for a binary tree node.
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10 class Solution {
11 public:
12 bool isBalanced(TreeNode* root) {
13 return balancedHeight (root) >= 0;
14 }
15 int balancedHeight (TreeNode* root) {
16 if (root == nullptr) return 0;
17 int left = balancedHeight (root->left);
18 int right = balancedHeight (root->right);
19 if (left < 0 || right < 0 || abs(left - right) > 1) return -1;
20 return max(left, right) + 1;
21 }
22 };