目录
题目
题目描述
编写程序判断给定的二叉树是否是平衡二叉树。
输入
二叉树的先序序列。
输出
如果是平衡二叉树,输出yes!,否者输出no!
样例输入
AB##C##样例输出
yes!
思路
首先,需要了解什么是平衡二叉树
平衡树(Balance Tree,BT) 指的是,任意节点的子树的高度差都小于等于1。常见的符合平衡树的有,B树(多路平衡搜索树)、AVL树(二叉平衡搜索树)等。
通俗来说,平衡二叉树的高度差不能大于1。
知道概念之后,那么平衡二叉树的判断方式就是分别求出左右子树的高度,然后作差,发现只要大于1,那么它就不是平衡二叉树了。
//求二叉树深度
int depth(BinaryTree* &root) {
if(root==NULL) return 0;
else return max(depth(root->left),depth(root->right))+1;
}
//判断是否为平衡二叉树
bool isBalanced(BinaryTree* &root) {
if(root==NULL) return true;
int leftDepth=depth(root->left);
int rightDepth=depth(root->right);
if(abs(leftDepth-rightDepth)>1) return false;//abs()函数表示取绝对值,abs(1)=abs(-1)=1
//判断左右子树是否也为平衡二叉树
return isBalanced(root->left) && isBalanced(root->right);
}
代码
#include <bits/stdc++.h>
using namespace std;
//定义
typedef struct BTNode {
char data;
BTNode *left;
BTNode *right;
}BinaryTree;
//创建二叉树
void Create(BinaryTree* &root) {
BTNode *q;
q=new BTNode;
cin>>q->data;
if(q->data=='#') {
root=q=NULL;
return;
}
root=q;
Create(root->left);
Create(root->right);
}
//求二叉树深度
int depth(BinaryTree* &root) {
if(root==NULL) return 0;
else return max(depth(root->left),depth(root->right))+1;
}
bool isBalanced(BinaryTree* &root) {
if(root==NULL) return true;
int leftDepth=depth(root->left);
int rightDepth=depth(root->right);
if(abs(leftDepth-rightDepth)>1) return false;
return isBalanced(root->left) && isBalanced(root->right);
}
int main() {
BinaryTree *root;
Create(root);
if(isBalanced(root)) cout<<"yes!";
else cout<<"no!";
return 0;
}