平衡搜索树的一种简单代码

public class AvlTree {
    //平衡二叉树不平衡有四种情况(去除对称其实只有两种)
    //即左左,右右,左右,右左(可自行画图脑补)
    //对应解决办法为 左旋 右旋 先左旋后右旋  先右旋后左旋
    //这里写的是最直观最简单也是效率比较低的写法
    class TreeNode{
        int val;
        int height;
        TreeNode left;
        TreeNode right;
        public TreeNode(int val){
            this.val=val;
        }
    }
    //获取树的高度
    public int height(TreeNode t){
        if(t==null){
            return -1;
        }else{
            return t.height;
        }
    }
    //leet获取高度
    public int height2(TreeNode t){
        if(t==null){
            return 0;
        }
        return 1+Math.max(height(t.left),height(t.right));
    }
    //插入节点
    public TreeNode insert(int val,TreeNode t){
        if(t==null){
            return new TreeNode(val);
        }
        if(val<t.val){
            //插入左子树
            t.left=insert(val,t.left);
        }else if(val>t.val){
            //插入右子树
            t.right=insert(val,t.right);
        }else{
            //不考虑重复节点情况,所以啥都不做
        }
        //是树成为平衡二叉树
        return  balance(t);
    }

    private TreeNode balance(TreeNode t) {
        if(t==null){
            return t;
        }
        if(height(t.left)-height(t.right)>1){
            if(height(t.left.left)>=height(t.left.right)){
                //左左情况,单旋
                t=rotateWithLeftChild(t);
            }else{
                //左右情况,双旋
                t=doubleWithRightChild(t);
            }
        }
        if(height(t.right)-height(t.left)>1){
            if(height(t.right.right)>=height(t.right.left)){
                //右右情况,单旋
                t=rotateWithRightChild(t);
            }else{
                //右左情况,双旋
                t=doubleWithLeftChild(t);
            }
        }
        t.height=Math.max(height(t.left),height(t.right))+1;
        return t;
    }
    //左右
    private TreeNode doubleWithRightChild(TreeNode t) {
        t.left=rotateWithLeftChild(t.left);
        return rotateWithRightChild(t);
    }
    //右左
    private TreeNode doubleWithLeftChild(TreeNode t) {
        t.right=rotateWithRightChild(t.right);
        return rotateWithLeftChild(t);
    }
    //右右
    private TreeNode rotateWithRightChild(TreeNode t) {
        TreeNode t1=t.right;
        TreeNode t2=t1.right;
        TreeNode t3=t1.left;
        t.right=t3;
        t1.left=t;
        return t1;

    }
    //左左
    private TreeNode rotateWithLeftChild(TreeNode t) {
        TreeNode t1=t.left;
        TreeNode t2=t1.left;
        TreeNode t3=t1.right;
        t.left=t3;
        t1.right=t;
        return t1;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值