Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 5bb595b

Browse files
Balanced BST
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent 63af633 commit 5bb595b

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

110_balanced_binary_tree/Makefile

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -O2 -o test balanced_bst.c
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <stdbool.h>
4+
5+
struct TreeNode {
6+
int val;
7+
struct TreeNode *left;
8+
struct TreeNode *right;
9+
};
10+
11+
static int depth(struct TreeNode* root, bool *balance)
12+
{
13+
if (!(*balance) || root == NULL) {
14+
return 0;
15+
}
16+
17+
int l = depth(root->left, balance) + 1;
18+
int r = depth(root->right, balance) + 1;
19+
if (*balance) {
20+
int diff = l > r ? l - r : r - l;
21+
*balance = diff < 2;
22+
}
23+
return l > r ? l : r;
24+
}
25+
26+
static bool isBalanced(struct TreeNode* root)
27+
{
28+
bool balance = true;
29+
depth(root, &balance);
30+
return balance;
31+
}
32+
33+
int main(void)
34+
{
35+
struct TreeNode root, n10, n11, n20, n21, n23, n30, n37;
36+
root.val = 1;
37+
n10.val = 2;
38+
n11.val = 3;
39+
n20.val = 4;
40+
n21.val = 5;
41+
n23.val = 6;
42+
n30.val = 7;
43+
n37.val = 8;
44+
root.left = &n10;
45+
root.right = &n11;
46+
n10.left = &n20;
47+
n10.right = &n21;
48+
n11.left = NULL;
49+
n11.right = &n23;
50+
n20.left = &n30;
51+
n20.right = NULL;
52+
n21.left = NULL;
53+
n21.right = NULL;
54+
n23.left = NULL;
55+
n23.right = &n37;
56+
n30.left = NULL;
57+
n30.right = NULL;
58+
n37.left = NULL;
59+
n37.right = NULL;
60+
61+
printf("%s\n", isBalanced(&root) ? "true" : "false");
62+
return 0;
63+
}

0 commit comments

Comments
 (0)