Skip to content

Commit 7ef5ab0

Browse files
authored
Create main.cpp
1 parent afc84ea commit 7ef5ab0

File tree

1 file changed

+32
-0
lines changed
  • 17 - Binary Tree Data Structure Problems/07 - Balanced Binary Tree

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
private:
14+
int height(TreeNode* root){
15+
if(root == NULL) return 0;
16+
17+
int left = height(root -> left);
18+
if(left == -1) return -1;
19+
20+
int right = height(root -> right);
21+
if(right == -1) return -1;
22+
23+
24+
if(abs(left - right) > 1) return -1;
25+
26+
return max(left, right) + 1;
27+
}
28+
public:
29+
bool isBalanced(TreeNode* root) {
30+
return height(root) != -1;
31+
}
32+
};

0 commit comments

Comments
 (0)