平衡二叉树 (AVL)
平衡二叉树的特点:每个节点的左右两个子树的高度差的绝对值不能超过1
示例 1:
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回 true
解题思路:这道题先进行错误,如果树为空,返回true
,否则判断两个子树的高度差是不是大于1,如果大于1返回false
,然后再递归到当前跟节点的左右节点接着判断。难点应该是我当时没有想出该如何计算当前节点的高度,这道题还是值得记一下的
/*
* @lc app=leetcode.cn id=110 lang=cpp
*
* [110] 平衡二叉树
*/
/**
* 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(get_height(root->left)-get_height(root->right))>1){
return false;
}
return isBalanced(root->left)&&isBalanced(root->right);
}
int get_height(TreeNode* root){
if(!root){
return 0;
}
return max(get_height(root->left),get_height(root->right))+1;
}
};