-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path110.cpp
36 lines (29 loc) · 854 Bytes
/
110.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
// 110. Balanced Binary Tree - https://leetcode.com/problems/balanced-binary-tree
#include <bits/stdc++.h>
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) {}
};
class Solution {
public:
int height(TreeNode* root) {
if (root == nullptr) { return 0; }
int left_height = height(root->left);
if (left_height == -1) { return -1; }
int right_height = height(root->right);
if (right_height == -1) { return -1; }
if (abs(left_height - right_height) > 1) return -1;
return max(left_height, right_height) + 1;
}
bool isBalanced(TreeNode* root) {
return height(root) != -1;
}
};
int main() {
ios::sync_with_stdio(false);
return 0;
}