一个左派堆实现

时间:2015-03-01 02:57:03

标签: java data-structures heap leftist-tree

所以我设法使用以下代码获得二进制左派堆的递归版本。

public class Node<T extends Comparable<T>>
{
    public T data;
    public Node<T> left;
    public Node<T> right;
    public int npl;

    public Node()
    {
        left = null;
        right = null;
        npl = 0;
    }
}

public class Leftist<T extends Comparable<T>>
{
    public Node<T> root;

    public Leftist()
    {
          root = null;
    }

    public void insert(T element)
    {
        if (root == null)
        {
            root = new Node();
        }
        else
        {
            Leftist temp = new Leftist();
            temp.insert(element);
            Merger(temp);
        }
    }

    public T remove()
    {

        T el = root.data;
        root = Merger(root.left, root.right);

        return el;
    }

    public Node<T> Merger(Node<T> old, Node<T> newer)
    {
        if (old == null)
            return newer;

        else if (newer == null)
            return old;
        else
        {
            if (old.data.compareTo(newer.data) < 0)
            {
                Node<T> temp = old;
                old = newer;
                old = temp;
            }
        }

        if (old.right == null)
            old.right = newer;
        else
            old.right = Merger (old.right, newer);

        if (old.left == null || old.right.npl > old.left.npl)
        {
            Node<T> temp = old.right;
            old.right = old.left;
            old.left = temp; 
        }

        if (old.right == null)
            old.npl = 0;
        else
            old.npl = old.right.npl + 1;

        return old;
    }
}

我想知道你们是否有可能帮助我搞清楚逻辑和调整左派堆的d-heap版本的代码,这是一个有n个子节点的左派堆。

真诚地感谢任何帮助。

0 个答案:

没有答案
相关问题