0%

平衡二叉树

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

AVL子树深度差小于1

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
class Solution {
public:
int get_depth(const TreeNode* pRoot)
{
if (pRoot == nullptr)
{
return 0;
}
else
{
const int left = get_depth(pRoot->left);
if (left == -1)
{
return -1;
}
else
{
const int right = get_depth(pRoot->right);
if (right == -1)
{
return -1;
}
else
{
if (abs(left - right) > 1)
{
return -1;
}
else
{
return max(left, right) + 1;
}
}
}
}
}
bool IsBalanced_Solution(TreeNode* pRoot) {
return get_depth(pRoot) != -1;
}
};