forked from soulmachine/algorithm-essentials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbalanced-binary-tree.cpp
More file actions
23 lines (19 loc) · 642 Bytes
/
balanced-binary-tree.cpp
File metadata and controls
23 lines (19 loc) · 642 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Balanced Binary Tree
// 时间复杂度O(n),空间复杂度O(logn)
class Solution {
public:
bool isBalanced (TreeNode* root) {
return balancedHeight (root) >= 0;
}
/**
* Returns the height of `root` if `root` is a balanced tree,
* otherwise, returns `-1`.
*/
int balancedHeight (TreeNode* root) {
if (root == nullptr) return 0; // 终止条件
int left = balancedHeight (root->left);
int right = balancedHeight (root->right);
if (left < 0 || right < 0 || abs(left - right) > 1) return -1; // 剪枝
return max(left, right) + 1; // 三方合并
}
};