-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path110-balance-binary-tree.cpp
59 lines (44 loc) · 1.02 KB
/
110-balance-binary-tree.cpp
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
using namespace std;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int tmp = 1;
int get_tree_d(TreeNode* root){
int d_left;
int d_right;
if(root == NULL) return 0;
d_left = get_tree_d(root->left);
d_right = get_tree_d(root->right);
if(abs(d_left - d_right) > 1) {
tmp = -1;
}
return (d_left > d_right)? d_left + 1: d_right + 1;
}
bool isBalanced(TreeNode* root) {
if(root == NULL) return true;
get_tree_d(root);
if(tmp == -1) return false;
else return true;
}
};
int main(){
Solution sol;
struct TreeNode root(0);
sol.isBalanced(&root);
return 0;
}