题目:输入一棵二叉树的根结点,判断该树是不是平衡二叉树。如果某二叉树中任意结点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。例如下图中的二叉树就是一棵平衡二叉树:
#include <iostream>参考文献:http://zhedahht.blog.163.com/blog/static/25411174201142733927831/
using namespace std;
struct BTNode{
BTNode *Left;
BTNode *Right;
int value;
BTNode(int val = 0)
:value(val){}
};
BTNode* CreateTree(){
int data;
cin >> data;
BTNode* root;
if(-1 == data)
return NULL;
else{
root = new BTNode(data);
root->Left = CreateTree();
root->Right = CreateTree();
}
return root;
}
bool IsBalancedBT(BTNode* pRoot,int *pDepth){
if(!pRoot){
*pDepth = 0;
return true;
}
int left,right;
if(IsBalancedBT(pRoot->Left,&left)
&&IsBalancedBT(pRoot->Right,&right)){
int diff = left - right;
if(diff<=1 && diff>=-1){
*pDepth = 1+(left>right?left:right);
return true;
}
}
return false;
}
bool IsBalanced(BTNode* root){
int depth = 0;
return IsBalancedBT(root,&depth);
}
void printTree(BTNode* root){
if(!root) return;
printTree(root->Left);
cout << root->value << " ";
printTree(root->Right);
return;
}
int main(){
BTNode* root = CreateTree();
printTree(root);
cout << endl;
if(IsBalanced(root))
cout << "The binary tree is balanced!" << endl;
return 0;
}