题目
题解
- 自顶向下:判断左右子树的高度差和左右子树是否为平衡树
- 自底向上:判断左右子树的高度差,进行剪枝操作
代码
/**
* 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 dfs(TreeNode* root){
// if(!root) return 0;
// else return max(dfs(root->left),dfs(root->right))+1;
// }
// bool isBalanced(TreeNode* root) {//左右子树高度差+左右子树是否平衡
// if(!root) return true;
// else return abs(dfs(root->left)-dfs(root->right))<=1&&isBalanced(root->left)&&isBalanced(root->right);
// }
// };
//自底向上
class Solution {
public:
int dfs(TreeNode* root){
if(!root) return 0;
int lh=dfs(root->left);
int rh=dfs(root->right);
if(lh==-1||rh==-1||abs(lh-rh)>1) return -1;
else return max(dfs(root->left),dfs(root->right))+1;
}
bool isBalanced(TreeNode* root) {//左右子树高度差+左右子树是否平衡
return dfs(root)!=-1;
}
};