# 检查一个二叉树是否平衡的算法分析与C++实现

``````struct TreeNode{
TreeNode *leftChild;
TreeNode *rightChild;
int data;
};

int getHeight(const TreeNode* root){
if( root == nullptr){
return 0;
}

return max(getHeight(root->leftChild), getHeight(root->rightChild)) + 1;
}

bool isBalanced(const TreeNode* root){
if( root == nullptr){
return true;
}

int heightDiff = abs(getHeight(root->leftChild) - getHeight(root->rightChild));
if( heightDiff > 1){
return false;
}
else{
return isBalanced(root->leftChild) && isBalanced(root->rightChild);
}
}``````

``````int checkHeight(const TreeNode* root){
if( root == nullptr){
return 0;
}
// check the left subtree is balanced or not.
int leftHeight = checkHeight(root->leftChild);
if( leftHeight == -1 ){
return -1;
}

// check the right subtree is balanced or not.
int rightHeight = checkHeight(root->rightChild);
if( rightHeight == -1){
return -1;
}

// check the current tree is balanced or not.
int diff = leftHeight - rightHeight;
if( abs(diff) > 1){
return -1;
}
else{
// return the tree height.
return max(leftHeight, rightHeight) + 1;
}
}
bool isBalanced(const TreeNode* root){
return ( checkHeight(root) == -1 )? false:true;
}
``````

原文作者：平衡二叉树
原文地址: https://blog.csdn.net/anzhsoft/article/details/17630715
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。