zoukankan      html  css  js  c++  java
  • 判断一棵二叉树是否为AVL树

    思路:AVL树是高度平衡的二叉搜索树,这里为了清晰说明,分别判断是否为搜索树,是否为平衡树。

    struct TreeNode
    {
        struct TreeNode *left;
        struct TreeNode *right;
        int key;
    };
    //这里先判断是否为二叉搜索树,其次判断是否为平衡的
    bool IsAVL(TreeNode *root,int depth)
    {
        if (isBST(root)&&isBalance(root,&depth))
        return true;
        return false;
    }
    
    //判断是否为二叉搜索树
    bool isBST(TreeNode *root)
    {
        if(root == NULL)return true;
        if (!isBST(root->left))return false;
        if (!isBST(root->right))return false;
        TreeNode *cur = root->left;
        if (cur != NULL)
        {
            while(cur->right!=NULL)cur = cur->right;
            if(root->key < cur->key)return false;
        }
        TreeNode *cur = root->right;
        if (cur != NULL)
        {
            while(cur->left!=NULL)cur = cur->left;
            if(root->key > cur->key)return false;
        }
        return true;
    }
    
    //判断是否平衡
    bool isBalance(TreeNode *root,int *depth)
    {
        if (root == NULL)
        {
            *depth = 0;
            return true;
        }
        int depthl,depthr;
        if(!isBalance(root->left,&depthl))return false;
        if(!isBalance(root->right,&depthr))return false;
        int diff = depthl - depthr;
        if(diff > 1 || diff < -1)return false;
        *depth = 1+(depthl>depthr?depthl:depthr);
        return true;
    }
  • 相关阅读:
    BZOJ1800 fly 飞行棋 [几何]
    Cf #434 Div.1 D Wizard's Tour [构造题]
    Last mile of the way [树形dp+重链剖分]
    World Of Our Own [Lucas+思维题]
    vue 初级小总结
    转-redux-saga
    【转】react-native开发混合App-github开源项目
    react中路由的跳转
    Lodash 浓缩
    jq的attr、prop和data区别
  • 原文地址:https://www.cnblogs.com/newpanderking/p/3969557.html
Copyright © 2011-2022 走看看