-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbalancedBinaryTree.cpp
83 lines (72 loc) · 1.7 KB
/
balancedBinaryTree.cpp
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <iostream>
#include <map>
#include <stdlib.h>
using std::cout;
using std::endl;
using std::map;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(root == NULL){
return true;
} else{
int result = depth(root);
if(result == -1){
return false;
} else{
return true;
}
}
}
int depth(TreeNode *node){
int leftdepth = 0;
int rightdepth = 0;
if(node == NULL){
return 0;
} else{
leftdepth = depth(node -> left);
rightdepth = depth(node -> right);
if(leftdepth == -1 || rightdepth == -1 || abs(leftdepth - rightdepth) > 1){
return -1;
} else{
return max(rightdepth, leftdepth) + 1;
}
}
}
};
int main(int argc, char const *argv[])
{
Solution test;
TreeNode *first = new TreeNode(1);
TreeNode *second = new TreeNode(2);
TreeNode *third = new TreeNode(3);
first -> right = second;
first -> left = third;
bool result = test.isBalanced(first);
if(result){
cout << "true" << endl;
} else{
cout << "false" << endl;
}
return 0;
}