-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathBalanced Binary Tree.cpp
More file actions
42 lines (38 loc) · 925 Bytes
/
Balanced Binary Tree.cpp
File metadata and controls
42 lines (38 loc) · 925 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
35
36
37
38
39
40
41
42
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
public:
bool isBalanced(TreeNode* root, int& depth)
{
if (root == nullptr)
{
depth = 0;
return true;
}
int left_depth = 0;
if (!isBalanced(root->left, left_depth))
{
return false;
}
int right_depth = 0;
if (!isBalanced(root->right, right_depth))
{
return false;
}
depth = max(left_depth, right_depth) + 1;
return (left_depth == right_depth || left_depth == right_depth + 1 || left_depth + 1 == right_depth);
}
bool isBalanced(TreeNode* root)
{
int depth = 0;
return isBalanced(root, depth);
}
};