1 自底向上的递归(推荐)
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
n
)
O(n)
O(n)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int recursive(TreeNode* root) {
if (!root) return 0;
int left = recursive(root->left);
if (left == -1) return -1;
int right = recursive(root->right);
if (right == -1) return -1;
if (abs(left - right) > 1)
return -1;
return max(left, right) + 1;
}
bool isBalanced(TreeNode* root) {
return recursive(root) != -1;
}
};
2 自顶向下的递归(不推荐)
时间复杂度:
O
(
n
2
)
O(n^2)
O(n2)
空间复杂度:
O
(
n
)
O(n)
O(n)
class Solution {
public:
int height(TreeNode* root) {
if (!root) return 0;
int left = height(root->left);
int right = height(root->right);
return max(left, right) + 1;
}
bool isBalanced(TreeNode* root) {
if (!root) return true;
return (abs( height(root->left) - height(root->right) ) < 2) && isBalanced(root->left) && isBalanced(root->right);
}
};
注意最后的条件是
abs( height(root->left) - height(root->right) ) < 2