-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path110.balanced-binary-tree.cpp
More file actions
45 lines (41 loc) · 1.04 KB
/
110.balanced-binary-tree.cpp
File metadata and controls
45 lines (41 loc) · 1.04 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
/*
* @lc app=leetcode id=110 lang=cpp
*
* [110] Balanced Binary Tree
*/
// @lc code=start
/**
* 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 {
public:
bool isBalanc = true;
int height(TreeNode* treeBalanced){
if(treeBalanced == nullptr){
return 0;
}
if(treeBalanced->left == nullptr && treeBalanced->right == nullptr){
return 1;
}
int left = height(treeBalanced->left);
int right = height(treeBalanced->right);
int h = 1 + max(left,right);
if(abs(left-right)>1){
isBalanc = false;
}
return h;
}
bool isBalanced(TreeNode* root) {
height(root);
return isBalanc;
}
};
// @lc code=end