-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path110_Balanced_Binary_Tree
56 lines (55 loc) · 1.4 KB
/
110_Balanced_Binary_Tree
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
Brute Force
/**
* 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 {
private:
int getDepth(TreeNode* node){
if (node == NULL) return 0;
return max(getDepth(node->left), getDepth(node->right)) + 1;
}
bool helper(TreeNode* node){
if (node == NULL) return true;
int left1 = getDepth(node->left);
int right1 = getDepth(node->right);
return abs(right1 - left1) <= 1 && helper(node->left) && helper(node->right);
}
public:
bool isBalanced(TreeNode* root) {
if (root == NULL) return true;
return helper(root);
}
};
Calculate depth + checking
/**
* 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 {
private:
bool result = true;
int getDepth(TreeNode* node){
if (node == NULL) return 0;
int left1 = getDepth(node->left);
int right1 = getDepth(node->right);
if (abs(left1 - right1) > 1) result = false;
return max(left1, right1) + 1;
}
public:
bool isBalanced(TreeNode* root) {
if (root == NULL) return true;
int trash = getDepth(root);
return result;
}
};