【题目描述】Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
【解题思路】平衡二叉树(Self-balancing binary search tree)又被称为AVL树(有别于AVL算法),且具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
据二叉平衡树的定义,我们先写一个求二叉树最大深度的函数。在主函数中,利用比较左右子树depth的差值来判断当前结点的平衡性,如果不满足则返回false。然后递归当前结点的左右子树,得到结果。
【考查内容】树
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int dfs(TreeNode* root){
if(root == NULL)
return 0;
return max(dfs(root->left), dfs(root->right)) + 1;
}
bool isBalanced(TreeNode* root) {
if(root == NULL)
return true;
if(abs( (dfs(root->left)) - dfs(root->right) ) > 1)
return false;
return (isBalanced(root->left) && isBalanced(root->right));
}
};