# 平衡二叉树-2

/**
* 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 judge(root) != -1;
}

int judge(TreeNode* root) {
if (!root) return 0;
int left = judge(root->left);
if (-1 == left) return -1;
int right = judge(root->right);
if (-1 == right) return -1;
return std::abs(left - right) <= 1 ? std::max(left, right) + 1 : -1;
}
};

/**
* 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 std::abs(depth(root->left) - depth(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}

int depth(TreeNode* root) {
if (!root) return 0;
return std::max(depth(root->left), depth(root->right)) + 1;
}
};

02-08 56
09-19 1088
07-24 9593
07-28 2411
05-14 1205
10-28 164
04-13 120
12-18 156
01-15 2181
08-31 346