forked from daiwb/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathisBalanced.cpp
More file actions
28 lines (27 loc) · 748 Bytes
/
Copy pathisBalanced.cpp
File metadata and controls
28 lines (27 loc) · 748 Bytes
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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int doit(TreeNode *root) {
if (root == NULL) return 0;
int h1 = doit(root->left);
int h2 = doit(root->right);
if (h1 == -1 || h2 == -1) return -1;
if (abs(h1 - h2) > 1) return -1;
return max(h1, h2) + 1;
}
bool isBalanced(TreeNode *root) {
if (root == NULL) return true;
int h1 = doit(root->left);
int h2 = doit(root->right);
if (h1 == -1 || h2 == -1 || abs(h1 - h2) > 1) return false;
return true;
}
};