题目大意:判断二叉树是否是AVL
分析:dfs整棵树判断每个结点的左右子树高度差是否大于1。可以自顶向下/自底向上(效率更高)。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(!root) return true;
if(abs(height(root->left)-height(root->right)) > 1) return false;
return isBalanced(root->left) && isBalanced(root->right);
}
int height(TreeNode* root) {
if(!root) return 0;
return max(height(root->left),height(root->right)) + 1;
}
};
自底向上:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
int height;
return helper(root,height);
}
bool helper(TreeNode* root,int& height){
if(!root){
height = -1;
return true;
}
int left,right;
if(helper(root->left,left) && helper(root->right,right) && abs(left - right) < 2){
height = max(left,right) + 1;
return true;
}
return false;
}
};