左傾堆(三)之 Java的實現


 

概要

前面分別通過C和C++實現了左傾堆,本章給出左傾堆的Java版本。還是那句老話,三種實現的原理一樣,擇其一了解即可。

目錄
1. 左傾堆的介紹
2. 左傾堆的圖文解析
3. 左傾堆的Java實現(完整源碼)
4. 左傾堆的Java測試程序

轉載請注明出處:http://www.cnblogs.com/skywang12345/p/3638384.html


更多內容:數據結構與算法系列 目錄

(01) 左傾堆(一)之 圖文解析 和 C語言的實現
(02) 左傾堆(二)之 C++的實現
(03) 左傾堆(三)之 Java的實現

 

左傾堆的介紹

左傾堆(leftist tree 或 leftist heap),又被成為左偏樹、左偏堆,最左堆等。
它和二叉堆一樣,都是優先隊列實現方式。當優先隊列中涉及到"對兩個優先隊列進行合並"的問題時,二叉堆的效率就無法令人滿意了,而本文介紹的左傾堆,則可以很好地解決這類問題。

 

左傾堆的定義

上圖是一顆左傾樹,它的節點除了和二叉樹的節點一樣具有左右子樹指針外,還有兩個屬性:鍵值和零距離。
(01) 鍵值的作用是來比較節點的大小,從而對節點進行排序。
(02) 零距離(英文名NPL,即Null Path Length)則是從一個節點到一個"最近的不滿節點"的路徑長度。不滿節點是指該該節點的左右孩子至少有有一個為NULL。葉節點的NPL為0,NULL節點的NPL為-1。

左傾堆有以下幾個基本性質:
[性質1] 節點的鍵值小於或等於它的左右子節點的鍵值。
[性質2] 節點的左孩子的NPL >= 右孩子的NPL。
[性質3] 節點的NPL = 它的右孩子的NPL + 1。

 

左傾堆的圖文解析

合並操作是左傾堆的重點。合並兩個左傾堆的基本思想如下:
(01) 如果一個空左傾堆與一個非空左傾堆合並,返回非空左傾堆。
(02) 如果兩個左傾堆都非空,那么比較兩個根節點,取較小堆的根節點為新的根節點。將"較小堆的根節點的右孩子"和"較大堆"進行合並。
(03) 如果新堆的右孩子的NPL > 左孩子的NPL,則交換左右孩子。
(04) 設置新堆的根節點的NPL = 右子堆NPL + 1

 

下面通過圖文演示合並以下兩個堆的過程。


提示這兩個堆的合並過程和測試程序相對應!

第1步:將"較小堆(根為10)的右孩子"和"較大堆(根為11)"進行合並。
合並的結果,相當於將"較大堆"設置"較小堆"的右孩子,如下圖所示:

 

第2步:將上一步得到的"根11的右子樹"和"根為12的樹"進行合並,得到的結果如下:

 

第3步:將上一步得到的"根12的右子樹"和"根為13的樹"進行合並,得到的結果如下:

 

第4步:將上一步得到的"根13的右子樹"和"根為16的樹"進行合並,得到的結果如下:

 

第5步:將上一步得到的"根16的右子樹"和"根為23的樹"進行合並,得到的結果如下:

至此,已經成功的將兩棵樹合並成為一棵樹了。接下來,對新生成的樹進行調節。

 

第6步:上一步得到的"樹16的右孩子的NPL > 左孩子的NPL",因此交換左右孩子。得到的結果如下:

 

第7步:上一步得到的"樹12的右孩子的NPL > 左孩子的NPL",因此交換左右孩子。得到的結果如下:

 

第8步:上一步得到的"樹10的右孩子的NPL > 左孩子的NPL",因此交換左右孩子。得到的結果如下:

至此,合並完畢。上面就是合並得到的左傾堆!


下面看看左傾堆的基本操作的代碼

1. 基本定義

public class LeftistHeap<T extends Comparable<T>> {

    private LeftistNode<T> mRoot;    // 根結點

    private class LeftistNode<T extends Comparable<T>> {
        T key;                    // 關鍵字(鍵值)
        int npl;                // 零路經長度(Null Path Length)
        LeftistNode<T> left;    // 左孩子
        LeftistNode<T> right;    // 右孩子

        public LeftistNode(T key, LeftistNode<T> left, LeftistNode<T> right) {
            this.key = key;
            this.npl = 0;
            this.left = left;
            this.right = right;
        }

        public String toString() {
            return "key:"+key;
        }
    }

    ...
}

LeftistNode是左傾堆對應的節點類。
LeftistHeap是左傾堆類,它包含了左傾堆的根節點,以及左傾堆的操作。

 

2. 合並

/*
 * 合並"左傾堆x"和"左傾堆y"
 */
private LeftistNode<T> merge(LeftistNode<T> x, LeftistNode<T> y) {
    if(x == null) return y;
    if(y == null) return x;

    // 合並x和y時,將x作為合並后的樹的根;
    // 這里的操作是保證: x的key < y的key
    if(x.key.compareTo(y.key) > 0) {
        LeftistNode<T> tmp = x;
        x = y;
        y = tmp;
    }

    // 將x的右孩子和y合並,"合並后的樹的根"是x的右孩子。
    x.right = merge(x.right, y);

    // 如果"x的左孩子為空" 或者 "x的左孩子的npl<右孩子的npl"
    // 則,交換x和y
    if (x.left == null || x.left.npl < x.right.npl) {
        LeftistNode<T> tmp = x.left;
        x.left = x.right;
        x.right = tmp;
    }
    if (x.right == null || x.left == null)
        x.npl = 0;
    else
        x.npl = (x.left.npl > x.right.npl) ? (x.right.npl + 1) : (x.left.npl + 1);

    return x;
}

public void merge(LeftistHeap<T> other) {
    this.mRoot = merge(this.mRoot, other.mRoot);
}

merge(x, y)是內部接口,作用是合並x和y這兩個左傾堆,並返回得到的新堆的根節點。
merge(other)是外部接口,作用是將other合並到當前堆中。


3. 添加

/* 
 * 新建結點(key),並將其插入到左傾堆中
 *
 * 參數說明:
 *     key 插入結點的鍵值
 */
public void insert(T key) {
    LeftistNode<T> node = new LeftistNode<T>(key,null,null);

    // 如果新建結點失敗,則返回。
    if (node != null)
        this.mRoot = merge(this.mRoot, node);
}

insert(key)的作用是新建鍵值為key的節點,並將其加入到當前左傾堆中。

 

4. 刪除

/* 
 * 刪除根結點
 * 
 * 返回值:
 *     返回被刪除的節點的鍵值
 */
public T remove() {
    if (this.mRoot == null)
        return null;

    T key = this.mRoot.key;
    LeftistNode<T> l = this.mRoot.left;
    LeftistNode<T> r = this.mRoot.right;

    this.mRoot = null;          // 刪除根節點
    this.mRoot = merge(l, r);   // 合並左右子樹

    return key;
}

remove()的作用是刪除左傾堆的最小節點。

 

注意關於左傾堆的"前序遍歷"、"中序遍歷"、"后序遍歷"、"打印"、"銷毀"等接口就不再單獨介紹了。后文的源碼中有給出它們的實現代碼,Please RTFSC(Read The Fucking Source Code)!

 

左傾堆的Java實現(完整源碼)

左傾堆的實現文件(LeftistHeap.java)

  1 /**
  2  * Java 語言: 左傾堆
  3  *
  4  * @author skywang
  5  * @date 2014/03/31
  6  */
  7 
  8 
  9 public class LeftistHeap<T extends Comparable<T>> {
 10 
 11     private LeftistNode<T> mRoot;    // 根結點
 12 
 13     private class LeftistNode<T extends Comparable<T>> {
 14         T key;                    // 關鍵字(鍵值)
 15         int npl;                // 零路經長度(Null Path Length)
 16         LeftistNode<T> left;    // 左孩子
 17         LeftistNode<T> right;    // 右孩子
 18 
 19         public LeftistNode(T key, LeftistNode<T> left, LeftistNode<T> right) {
 20             this.key = key;
 21             this.npl = 0;
 22             this.left = left;
 23             this.right = right;
 24         }
 25 
 26         public String toString() {
 27             return "key:"+key;
 28         }
 29     }
 30 
 31     public LeftistHeap() {
 32         mRoot = null;
 33     }
 34 
 35     /*
 36      * 前序遍歷"左傾堆"
 37      */
 38     private void preOrder(LeftistNode<T> heap) {
 39         if(heap != null) {
 40             System.out.print(heap.key+" ");
 41             preOrder(heap.left);
 42             preOrder(heap.right);
 43         }
 44     }
 45 
 46     public void preOrder() {
 47         preOrder(mRoot);
 48     }
 49 
 50     /*
 51      * 中序遍歷"左傾堆"
 52      */
 53     private void inOrder(LeftistNode<T> heap) {
 54         if(heap != null) {
 55             inOrder(heap.left);
 56             System.out.print(heap.key+" ");
 57             inOrder(heap.right);
 58         }
 59     }
 60 
 61     public void inOrder() {
 62         inOrder(mRoot);
 63     }
 64 
 65     /*
 66      * 后序遍歷"左傾堆"
 67      */
 68     private void postOrder(LeftistNode<T> heap) {
 69         if(heap != null)
 70         {
 71             postOrder(heap.left);
 72             postOrder(heap.right);
 73             System.out.print(heap.key+" ");
 74         }
 75     }
 76 
 77     public void postOrder() {
 78         postOrder(mRoot);
 79     }
 80 
 81     /*
 82      * 合並"左傾堆x"和"左傾堆y"
 83      */
 84     private LeftistNode<T> merge(LeftistNode<T> x, LeftistNode<T> y) {
 85         if(x == null) return y;
 86         if(y == null) return x;
 87 
 88         // 合並x和y時,將x作為合並后的樹的根;
 89         // 這里的操作是保證: x的key < y的key
 90         if(x.key.compareTo(y.key) > 0) {
 91             LeftistNode<T> tmp = x;
 92             x = y;
 93             y = tmp;
 94         }
 95 
 96         // 將x的右孩子和y合並,"合並后的樹的根"是x的右孩子。
 97         x.right = merge(x.right, y);
 98 
 99         // 如果"x的左孩子為空" 或者 "x的左孩子的npl<右孩子的npl"
100         // 則,交換x和y
101         if (x.left == null || x.left.npl < x.right.npl) {
102             LeftistNode<T> tmp = x.left;
103             x.left = x.right;
104             x.right = tmp;
105         }
106         if (x.right == null || x.left == null)
107             x.npl = 0;
108         else
109             x.npl = (x.left.npl > x.right.npl) ? (x.right.npl + 1) : (x.left.npl + 1);
110 
111         return x;
112     }
113 
114     public void merge(LeftistHeap<T> other) {
115         this.mRoot = merge(this.mRoot, other.mRoot);
116     }
117 
118     /* 
119      * 新建結點(key),並將其插入到左傾堆中
120      *
121      * 參數說明:
122      *     key 插入結點的鍵值
123      */
124     public void insert(T key) {
125         LeftistNode<T> node = new LeftistNode<T>(key,null,null);
126 
127         // 如果新建結點失敗,則返回。
128         if (node != null)
129             this.mRoot = merge(this.mRoot, node);
130     }
131 
132     /* 
133      * 刪除根結點
134      * 
135      * 返回值:
136      *     返回被刪除的節點的鍵值
137      */
138     public T remove() {
139         if (this.mRoot == null)
140             return null;
141 
142         T key = this.mRoot.key;
143         LeftistNode<T> l = this.mRoot.left;
144         LeftistNode<T> r = this.mRoot.right;
145 
146         this.mRoot = null;          // 刪除根節點
147         this.mRoot = merge(l, r);   // 合並左右子樹
148 
149         return key;
150     }
151 
152     /*
153      * 銷毀左傾堆
154      */
155     private void destroy(LeftistNode<T> heap) {
156         if (heap==null)
157             return ;
158 
159         if (heap.left != null)
160             destroy(heap.left);
161         if (heap.right != null)
162             destroy(heap.right);
163 
164         heap=null;
165     }
166 
167     public void clear() {
168         destroy(mRoot);
169         mRoot = null;
170     }
171 
172     /*
173      * 打印"左傾堆"
174      *
175      * key        -- 節點的鍵值 
176      * direction  --  0,表示該節點是根節點;
177      *               -1,表示該節點是它的父結點的左孩子;
178      *                1,表示該節點是它的父結點的右孩子。
179      */
180     private void print(LeftistNode<T> heap, T key, int direction) {
181 
182         if(heap != null) {
183 
184             if(direction==0)    // heap是根節點
185                 System.out.printf("%2d(%d) is root\n", heap.key, heap.npl);
186             else                // heap是分支節點
187                 System.out.printf("%2d(%d) is %2d's %6s child\n", heap.key, heap.npl, key, direction==1?"right" : "left");
188 
189             print(heap.left, heap.key, -1);
190             print(heap.right,heap.key,  1);
191         }
192     }
193 
194     public void print() {
195         if (mRoot != null)
196             print(mRoot, mRoot.key, 0);
197     }
198 }
View Code

左傾堆的測試程序(LeftistHeapTest.java)

 1 /**
 2  * Java 語言: 左傾堆
 3  *
 4  * @author skywang
 5  * @date 2014/03/31
 6  */
 7 
 8 public class LeftistHeapTest {
 9 
10     public static void main(String[] args) {
11         int a[]= {10,40,24,30,36,20,12,16};
12         int b[]= {17,13,11,15,19,21,23};
13         LeftistHeap<Integer> ha=new LeftistHeap<Integer>();
14         LeftistHeap<Integer> hb=new LeftistHeap<Integer>();
15 
16         System.out.printf("== 左傾堆(ha)中依次添加: ");
17         for(int i=0; i<a.length; i++) {
18             System.out.printf("%d ", a[i]);
19             ha.insert(a[i]);
20         }
21         System.out.printf("\n== 左傾堆(ha)的詳細信息: \n");
22         ha.print();
23 
24 
25         System.out.printf("\n== 左傾堆(hb)中依次添加: ");
26         for(int i=0; i<b.length; i++) {
27             System.out.printf("%d ", b[i]);
28             hb.insert(b[i]);
29         }
30         System.out.printf("\n== 左傾堆(hb)的詳細信息: \n");
31         hb.print();
32 
33         // 將"左傾堆hb"合並到"左傾堆ha"中。
34         ha.merge(hb);
35         System.out.printf("\n== 合並ha和hb后的詳細信息: \n");
36         ha.print();
37     }
38 }
View Code

 

左傾堆的Java測試程序

左傾堆的測試程序已經包含在它的實現文件(LeftistHeapTest.java)中了,這里僅給出它的運行結果:

== 左傾堆(ha)中依次添加: 10 40 24 30 36 20 12 16 
== 左傾堆(ha)的詳細信息: 
10(2) is root
24(1) is 10's   left child
30(0) is 24's   left child
36(0) is 24's  right child
12(1) is 10's  right child
20(0) is 12's   left child
40(0) is 20's   left child
16(0) is 12's  right child

== 左傾堆(hb)中依次添加: 17 13 11 15 19 21 23 
== 左傾堆(hb)的詳細信息: 
11(2) is root
15(1) is 11's   left child
19(0) is 15's   left child
21(0) is 15's  right child
13(1) is 11's  right child
17(0) is 13's   left child
23(0) is 13's  right child

== 合並ha和hb后的詳細信息: 
10(2) is root
11(2) is 10's   left child
15(1) is 11's   left child
19(0) is 15's   left child
21(0) is 15's  right child
12(1) is 11's  right child
13(1) is 12's   left child
17(0) is 13's   left child
16(0) is 13's  right child
23(0) is 16's   left child
20(0) is 12's  right child
40(0) is 20's   left child
24(1) is 10's  right child
30(0) is 24's   left child
36(0) is 24's  right child

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM