-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbalanced-binary-tree.cpp
More file actions
47 lines (41 loc) · 1.18 KB
/
balanced-binary-tree.cpp
File metadata and controls
47 lines (41 loc) · 1.18 KB
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
// https://leetcode.com/problems/balanced-binary-tree/submissions/1476388728/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
//find height of each node starting from the leftside, bottom to top
public:
int isB(TreeNode* root){
if(!root){
return 0;
}
//depth of left side, recursive until null. null makes int leftdepth = 0. +1 added per row
int leftdepth = isB(root->left);
if(leftdepth == -1){
return -1;
}
int rightdepth = isB(root->right);
if(rightdepth == -1){
return -1;
}
if(abs(leftdepth - rightdepth) > 1){
return -1;
}
return 1 + fmax(leftdepth, rightdepth);
}
bool isBalanced(TreeNode* root) {
if(!root){
return true;
}else{
return isB(root) != -1;
}
}
};