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.
Subscribe to see which companies asked this question
思路分析:
在AVL树中任何节点的两个子树的高度最大差别为一,所以它也被称为高度平衡树。
AVL树本质上还是一棵二叉搜索树(因此读者可以看到我后面的代码是继承自二叉搜索树的),它的特点是:
1. 本身首先是一棵二叉搜索树。
2. 带有平衡条件:每个结点的左右子树的高度之差的绝对值(平衡因子)最多为1。
AVL树是最先发明的自平衡二叉查找树。在AVL树中任何节点的两个子树的高度最大差别为一,所以它也被称为高度平衡树。查找、插入和删除在平均和最坏情况下都是O(log n)。增加和删除可能需要通过一次或多次树旋转来重新平衡这个树。
节点的平衡因子是它的左子树的高度减去它的右子树的高度(有时相反)。带有平衡因子1、0或 -1的节点被认为是平衡的。带有平衡因子 -2或2的节点被认为是不平衡的,并需要重新平衡这个树。平衡因子可以直接存储在每个节点中,或从可能存储在节点中的子树高度计算出来。
一般我们所看见的都是排序平衡二叉树
class Solution {
public:
int maxDepth(TreeNode * root){
if (root==NULL){return 0;}
return 1+max(maxDepth(root->left),maxDepth(root->right));
}
bool testNode(TreeNode * root){
if (root==NULL) {return true;}
if (abs(maxDepth(root->left) - maxDepth(root->right)) >1) {return false;}
return (testNode(root->left) && testNode(root->right));
}
bool isBalanced(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return testNode(root);
}
};