数据结构与算法-java实现左式堆

左式堆最难理解的就是合并操作了,实际就是记住一句话:根植大的堆和根植小的堆的右子树合并。可参考下图:(以下图片来自于https://blog.csdn.net/yangtrees/article/details/8252760

                           

(1)H1只有一个节点

(2)H1无右子节点

(3)H1有右子节点

                               

                                              

        

                              

代码如下:

package com_DataStructureAndAlogorithm_Learning;

public class LeftistHeap_2<AnyType extends Comparable<? super AnyType>> {
    private LeftistNode<AnyType> root;

    private static class LeftistNode<AnyType> {
        LeftistNode(AnyType theElement) {
            this(theElement, null, null);
        }

        LeftistNode(AnyType theElement, LeftistNode<AnyType> lt, LeftistNode<AnyType> rt) {
            element = theElement;
            left = lt;
            right = rt;
            npl = 0;
        }

        AnyType element;
        LeftistNode<AnyType> left;
        LeftistNode<AnyType> right;
        int npl;
    }

    public LeftistHeap_2() {
        root = null;
    }

    public void merge(LeftistHeap_2 rhs) {
        if (this == rhs) return;

        root = merge(root, rhs.root);
        rhs.root = null;
    }

    private LeftistNode<AnyType> merge(LeftistNode<AnyType> h1, LeftistNode<AnyType> h2) {
        if (h1 == null) {
            return h2;
        } else if (h2 == null) {
            return h1;
        }

        if (h1.element.compareTo(h2.element) < 0) {
            return merge1(h1, h2);
        } else {
            return merge1(h2, h1);
        }
    }

    private LeftistNode<AnyType> merge1(LeftistNode<AnyType> h1, LeftistNode<AnyType> h2) {
        if (h1.left == null) {
            h1.left = h2;
        } else {
            h1.right = merge(h1.right, h2);
            if (h1.left.npl < h1.right.npl) {
                swapChildren(h1);
            }
            h1.npl = h1.right.npl +1;
        }
        return h1;
    }

    private static <AnyType> void swapChildren(LeftistNode<AnyType> t) {
        LeftistNode<AnyType> tmp = t.left;
        t.left = t.right;
        t.right = tmp;
    }

    public void insert(AnyType x) {
        root = merge(new LeftistNode<AnyType>(x), root);
    }

    public AnyType findMin() {
        if (isEmpty()) {
            System.out.println("error");
        }
        return root.element;
    }

    public boolean isEmpty() {
        return root == null;
    }

    public void makeEmpty() {
        root = null;
    }

    public AnyType deleteMin() {
        if (isEmpty()) {
            System.out.println("error");
        }

        AnyType minItem = root.element;
        root = merge(root.left, root.right);
        return minItem;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值