-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbalancedbst.cpp
97 lines (77 loc) · 1.85 KB
/
balancedbst.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// {"category": "H-1B", "notes": "Binary Search Tree is balanced"}
#include <SDKDDKVer.h>
#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
//------------------------------------------------------------------------------
//
// Write a function to check if a Binary Search Tree is balanced.
//
// Source: http://www.bbc.com/news/blogs-trending-39127617
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//
// Implementation
//
//------------------------------------------------------------------------------
struct node
{
int data;
struct node* left;
struct node* right;
node(int data);
};
int height(struct node* node)
{
if (node == nullptr)
{
return 0;
}
return 1 + max(height(node->left), height(node->right));
}
bool isBalanced(struct node* root)
{
if (root == nullptr)
{
return true;
}
int lh = height(root->left);
int rh = height(root->right);
if (abs(lh - rh) <= 1 &&
isBalanced(root->left) &&
isBalanced(root->right))
{
return true;
}
return false;
}
//------------------------------------------------------------------------------
//
// Demo execution
//
//------------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
struct node *root = &node(1);
root->left = &node(2);
root->right = &node(3);
root->left->left = &node(4);
root->left->right = &node(5);
root->left->left->left = &node(8);
if (isBalanced(root))
{
printf("Tree is balanced\n");
}
else
{
printf("Tree is not balanced\n");
}
return 0;
}
node::node(int data)
{
this->data = data;
this->left = nullptr;
this->right = nullptr;
}