SWUST OJ#1077 平衡二叉树的判定

目录

题目

思路

代码


题目

题目描述

编写程序判断给定的二叉树是否是平衡二叉树。

输入

二叉树的先序序列。

输出

如果是平衡二叉树,输出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;
}

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青衿白首志

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值