-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy path110.isBalanced.cpp
More file actions
34 lines (30 loc) · 959 Bytes
/
110.isBalanced.cpp
File metadata and controls
34 lines (30 loc) · 959 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
29
30
31
32
33
34
/**
* 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:
int count(TreeNode* node) {
if (node == NULL) return 0;
int level = max(count(node->left), count(node->right))+1;
node->val = level;
return level;
}
bool dfs(TreeNode* root) {
if (root == NULL) return true;
if (root->left == NULL && root->right == NULL) return true;
if (root->left == NULL && root->right->val > 1) return false;
if (root->right == NULL && root->left->val > 1) return false;
if (root->right != NULL && root->left != NULL && abs(root->right->val - root->left->val) > 1) return false;
return dfs(root->left) && dfs(root->right);
}
bool isBalanced(TreeNode* root) {
count(root);
return dfs(root);
}
};