判断一棵树是否为AVL树

NO.12

判断一棵树是否为AVL树:

平衡二叉树(AVL树)是满足下面条件的二叉树:要么是一棵空树,要么左右子树都是AVL树,并且左右子树的深度之差的绝对值不大于1。由此可知,要判断一棵树是不是AVL树,只要判断它的左右子树的深度之差。问题落到了如何求一棵树的深度上去了。下面使用递归的方法求一棵树的深度:

#include<stdio.h>  
#include<math.h>  
#include<malloc.h>  
typedef struct BTree  
{  
    int data;  
    struct BTree *lchild,*rchild;  
}BTree,*Root;  
int isAVL(Root root)  
{  
    if(!root)  
                return TRUE;  
        int ldepth=getDepth(root->lchild);  
        int rdepth=getDepth(root->rchild);  
        int abs_depth=abs(ldepth-rdepth);  
        printf("ldepth=%d,rdepth=%d\n",ldepth,rdepth);  
        return (abs_depth<=1)&&isAVL(root->lchild)&&isAVL(root->rchild);  
}  
int getDepth(Root root)  
{  
    int  ldepth,rdepth;  
    if(!root)  
        return  0;  
    else  
    {  
        rdepth=getDepth(root->rchild);  
        ldepth=getDepth(root->lchild);  
        return (rdepth>ldepth)?(rdepth+1):(ldepth+1);  
    }  
}  
Root createBTree(int arr[],int len,int i)  
{  
    Root root;  
    if(i>=len||(arr[i]==0))  
        return NULL;  
//  printf("i=%d,len=%d,arr[i]=%d\n",i,len,arr[i]);  
    root=(Root)malloc(sizeof(BTree));  
    root->data=arr[i];  
    root->lchild=createBTree(arr,len,2*i);  
    root->rchild=createBTree(arr,len,2*i+1);  

    return root;  
}  
void destroyBtree()  
{  

}  
int main(void)  
{  
    int arr[]={0,1,2,3,4,0,0,0};  
    //int arr[]={0,1,2,0,4,0,0,0,8};  
    int i,depth;  
    //Root root=createBTree(arr,9,1);  
    Root root=createBTree(arr,8,1);  
//  if(root)        printf("ok\n");  
    printf("depth=%d",getDepth(root));  
    if(isAVL(root))  
        printf("是AVL树\n");  
    else  
        printf("不是AVL树");  
}  
判断一棵二叉树是否为 AVL 树,需要满足以下两个条件: 1. 该二叉树的所有子树都是 AVL 树; 2. 该二叉树的任意两个子树高度差的绝对值不超过 1。 其中,子树的高度指的是该子树的根节点到叶子节点的最长路径长度。 因此,判断一棵二叉树是否为 AVL 树,需要对该二叉树进行递归遍历,依次判断每个子树是否为 AVL 树,并计算每个子树的高度,最后再判断任意两个子树高度差的绝对值是否不超过 1。如果满足以上两个条件,则该二叉树为 AVL 树,否则不是 AVL 树。 具体实现过程可以参考以下代码(假设二叉树的节点结构为 Node,其包含 left、right、height 三个属性): ```python def is_avl_tree(root): # 辅助函数,计算节点高度 def get_height(node): if not node: return 0 return node.height # 判断一棵二叉树是否为 AVL 树 def is_avl_tree_helper(node): if not node: return True # 判断左右子树是否为 AVL 树 if not is_avl_tree_helper(node.left) or not is_avl_tree_helper(node.right): return False # 计算左右子树的高度差 height_diff = abs(get_height(node.left) - get_height(node.right)) if height_diff > 1: return False # 更新当前节点的高度 node.height = max(get_height(node.left), get_height(node.right)) + 1 return True # 判断根节点是否为空,为空则返回 False if not root: return False return is_avl_tree_helper(root) ``` 注意,以上代码仅为示例,具体实现可能因语言和实际情况的不同而有所差异。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值