-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBalancedBinaryTree.h
54 lines (43 loc) · 1.05 KB
/
BalancedBinaryTree.h
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
51
52
53
54
//
// Created by Zhao,Hongyan on 2020/3/9.
//
#ifndef LEETCODE_BALANCEDBINARYTREE_H
#define LEETCODE_BALANCEDBINARYTREE_H
#endif //LEETCODE_BALANCEDBINARYTREE_H
#include "TreeNode.h"
#include <math.h>
using namespace std;
class Solution {
public:
bool isBalanced(TreeNode* root) {
if (root == NULL) {
return true;
}
int left = 0;
int right = 0;
if(root->left){
left = high(root->left);
}
if(root->right){
right = high(root->right);
}
return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
int high(TreeNode* root){
if(root == NULL) {
return 0;
}
if(root->right == NULL && root ->left == NULL){
return 1;
}
int left = 0;
int right = 0;
if(root->right){
right = high(root->right);
}
if(root->left) {
left = high(root->left) ;
}
return right > left ? right + 1 : left + 1;
}
};