-
Notifications
You must be signed in to change notification settings - Fork 0
/
balanced-binary-tree.cpp
50 lines (42 loc) · 1.13 KB
/
balanced-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
/**
* 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:
bool isBalanced(TreeNode* root) {
if (root == NULL){
return true;
}
int left_depth = dfs(root->left,1);
int right_depth = dfs(root->right,1);
if (abs(left_depth - right_depth) > 1){
return false;
}
else{
return isBalanced(root->left) && isBalanced(root->right);
}
}
int dfs(TreeNode* root,int depth){
if (root == NULL){
return 0;
}
if (root->left == NULL && root->right == NULL){
return depth;
}
int left_depth = 0;
if (root->left != NULL){
left_depth = dfs(root->left, depth+1);
}
int right_depth = 0;
if (root->right != NULL){
right_depth = dfs(root->right, depth+1);
}
return max(left_depth, right_depth);
}
};