-
Notifications
You must be signed in to change notification settings - Fork 980
/
solution.h
40 lines (36 loc) · 871 Bytes
/
solution.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <complex>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool isBalanced(TreeNode *root) {
height(root);
return bBalanced;
}
private:
int height(TreeNode *node)
{
if (node == NULL || !bBalanced) return 0;
else
{
int leftHeight = height(node->left);
int rightHeight = height(node->right);
if (std::abs(leftHeight - rightHeight) > 1) bBalanced = false;
return std::max(leftHeight, rightHeight) + 1;
}
}
bool bBalanced = true;
};