-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalancedBinaryTree.cpp
More file actions
66 lines (60 loc) · 1.35 KB
/
BalancedBinaryTree.cpp
File metadata and controls
66 lines (60 loc) · 1.35 KB
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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/***
* 法1:递归求树深,然后比较左右子树
* 并递归分别判断左右子树
* 缺点:会重复求树深
***/
/*
class Solution {
public:
int treeDepth(TreeNode *root)
{
if (NULL == root)
return 0;
return max(treeDepth(root->left), treeDepth(root->right)) + 1;
}
bool isBalanced(TreeNode *root) {
if (NULL == root)
return true;
int depl = treeDepth(root->left);
int depr = treeDepth(root->right);
int diff = abs(depl - depr);
if (diff > 1)
return false;
return isBalanced(root->left) && isBalanced(root->right);
}
};
*/
/***
* 法2:一边遍历求树深,一边判断是否平衡
***/
class Solution {
public:
bool isBalanced(TreeNode *root) {
int h;
return isBalRec(root, h);
}
private:
bool isBalRec(TreeNode *root, int &height)
{
if (!root)
{
height = 0;
return true;
}
int lh = 0;
int rh = 0;
if (!isBalRec(root->left, lh) || !isBalRec(root->right, rh))
return false;
height = max(lh, rh) + 1;
return (abs(lh - rh) <= 1);
}
};