zl程序教程

您现在的位置是:首页 >  后端

当前栏目

笔记:武汉理工大学2017年计算机考研复试 算法笔试题解3

算法笔记计算机 2017 笔试 题解 考研 复试
2023-09-27 14:19:45 时间

题目:写出一个判断平衡二叉树的算法。

题解:

#include<iostream>
#include<stdio.h>

using namespace std;

typedef struct node{
    int val;
    node* left;
    node* right;
}treeNode;

int BinaryTreeHigh(treeNode* root)//求树的高度
{
    if(root==NULL)
    {
        return 0;
    }
    int high1 = BinaryTreeHigh(root->left);
    int high2 = BinaryTreeHigh(root->right);

    return high1>high2? high1+1:high2+1;//左、右中取最大,然后+1
}

int IsBlancedTree(treeNode* root)//判断平衡
{
    if(root==NULL)//为空则是平衡
    {
        return 1;
    }
    int right =BinaryTreeHigh(root->right);
    int left =BinaryTreeHigh(root->left);
    int gap =right - left;//返回右子树和左子树的差值
    if(gap>1||gap<-1)
        return 0;
    return IsBlancedTree(root->left)&&IsBlancedTree(root->right);//递归
}