oj题解-判别平衡二叉树

该代码实现了一个用于判断给定中序和层序遍历序列是否对应一棵平衡二叉树的算法。通过创建二叉树并计算各节点深度,检查是否满足平衡条件(任意节点左右子树深度差不超过1)。对于样例输入,代码能够正确判断并输出结果。
摘要由CSDN通过智能技术生成

题目描述

给定一棵二叉树的中序和层序输出,判断是否为平衡二叉树的。如果是,输出YES如果不是输出NO。

输入

树结点个数

中序遍历序列
层序遍历序列

输出

是否是平衡二叉树的判断结论

样例输入

样例1:
3
1 2 3
2 1 3
样例2:
4
1 2 3 4
1 2 3 4

样例输出

样例1:
YES
样例2:
NO
代码如下:

#include<iostream>
#include<queue>
#include<cmath>
using namespace std;
int layer[10000], in[10000];
int n;
template<typename T>
struct TreeNode
{
    T data;
    TreeNode<T>*  lchild;
    TreeNode<T>* rchild;
    TreeNode(TreeNode<T>* lc=NULL, TreeNode<T>* rc=NULL):lchild(lc),rchild(rc) {}
    TreeNode(const T& elem, TreeNode<T>* lc=NULL, TreeNode<T>* rc=NULL):data(elem),lchild(lc),rchild(rc) {}

};
template<typename T>
class BinaryTree
{
private:
    TreeNode<T>* root;
public:
    BinaryTree( int ll,int lr,int inl,int inr)
    {
        root=TreeCreate(ll,lr,inl,inr);
    }
    TreeNode<T>* TreeCreate(int ll, int lr, int inl, int inr)
    {
        if(inl>inr)
            return NULL;
        TreeNode<T> *t = new TreeNode<T>();//因为每次递归返回的是一个结点,所以需要每次分配空间
        int i,j;
        bool f;
        for(i = ll; i<=lr; i++)
        {
            f = false;
            for(j = inl; j<=inr; j++)
            {
                if(layer[i] == in[j])
                {
                    t->data = in[j];
                    t->lchild = NULL;
                    t->rchild = NULL;
                    f = true;
                    break;
                }
            }
            if(f)//如果找到了结点就出去
                break;
        }
        if(!f)
            return NULL;
        if(j > inl)//递归如果位置大于中序左边的位置
            t->lchild = TreeCreate(0, n-1, inl, j-1);//为什么是从零开始,这里的n是全局变量。注意左孩子,从找到的根节点划分左子树。
        if(j < inr)
            t->rchild = TreeCreate(0, n-1, j+1, inr);
        return t;
    }
    TreeNode<T>* getNode()
    {
        return root;
    }
    int GetDepth(TreeNode<T>* r)
{
    int depth;
    int ld, rd;
    if(!r)
        return 0;
    else
    {
        ld = GetDepth(r->lchild);
        rd = GetDepth(r->rchild);
        depth = ld > rd  ? ld :rd;
        return depth+1;
    }
}
int IsAVL(TreeNode<T>* root)
{
      if(root==NULL)
        return 1;
    int ldepth = GetDepth(root->lchild);
    int rdepth = GetDepth(root->rchild);
    int abs_depth = abs(ldepth-rdepth);
    return (abs_depth <= 1) && IsAVL(root->lchild)&& IsAVL(root->rchild);
}
};
int main()
{

    cin>>n;
    int i;
    for(i=0; i<n; i++)
        cin>>in[i];
    for( i=0; i<n; i++)
        cin>>layer[i];
    BinaryTree<int> bt(0,n,0,n);
    if(bt.IsAVL(bt.getNode())==0)
        cout<<"No";
    else
        cout<<"Yes";
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值