-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoffer-55-02-BalancedBinaryTree.c
92 lines (76 loc) · 1.36 KB
/
offer-55-02-BalancedBinaryTree.c
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
#include <stdio.h>
#include <stdbool.h>
#include "minunit.h"
// https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/
#define max(a, b) (a > b ? a : b)
/**
* Definition for a binary tree node.
*/
struct TreeNode
{
int val;
struct TreeNode *left;
struct TreeNode *right;
};
int dfs(struct TreeNode *root)
{
if (root == NULL)
{
return 0;
}
int left = dfs(root->left);
int right = dfs(root->right);
return max(left, right) + 1;
}
bool isBalanced(struct TreeNode *root)
{
if (root == NULL)
{
return true;
}
int left = dfs(root->left);
int right = dfs(root->right);
if (left - right > 1 || right - left < -1)
{
return false;
}
return isBalanced(root->left) && isBalanced(root->right);
}
bool helper(struct TreeNode *pRoot, int *pDepth)
{
if (pRoot == NULL)
{
*pDepth = 0;
return true;
}
int left, right;
if (helper(pRoot->left, &left) && helper(pRoot->right, &right))
{
int diff = left - right;
if (diff <= 1 && diff >= -1)
{
*pDepth = 1 + (left > right ? left : right);
return true;
}
}
return false;
}
bool isBalanced2(struct TreeNode *root)
{
int depth = 0;
return helper(root, &depth);
}
MU_TEST(test_case)
{
mu_check(5 == 7);
}
MU_TEST_SUITE(test_suite)
{
MU_RUN_TEST(test_case);
}
int main()
{
MU_RUN_SUITE(test_suite);
MU_REPORT();
return MU_EXIT_CODE;
}