本文實(shí)例講述了java使用歸并刪除法刪除二叉樹中節(jié)點(diǎn)的方法。分享給大家供大家參考。具體分析如下:
實(shí)現(xiàn)的思想很簡(jiǎn)單:
first:找到要?jiǎng)h除的節(jié)點(diǎn)
second:如果刪除的節(jié)點(diǎn)沒(méi)有右子樹那么左子樹鏈到父節(jié)點(diǎn)
third:如果刪除的節(jié)點(diǎn)沒(méi)有左子樹那么右子樹鏈到父節(jié)點(diǎn)
forth:如果刪除的節(jié)點(diǎn)又左右孩子,那么可以歸并刪除節(jié)點(diǎn)后的子樹:方法有兩種一種是用刪除節(jié)點(diǎn)的左子樹的最右節(jié)點(diǎn),指向刪除節(jié)點(diǎn)的右子樹,另一種是用刪除節(jié)點(diǎn)的用字?jǐn)?shù)的最左節(jié)點(diǎn)指向刪除節(jié)點(diǎn)的左子樹。
Java 實(shí)現(xiàn)如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
public void deleteByMerging( int el) { IntBSTNode tmp,node,p=root,prev= null ; /*find the node to be deleted*/ while(p!=null&&p.key!=el) { prev=p; if(p.key<el) p=p.right; else p=p.left; } /*find end*/ node=p; if (p!= null &&p.key==el) { if (node.right== null ) //node has no right child then its left child (if any) is attached to node=node.left; //its parent else if (node.left== null ) //node has no left child then its right child (if any) is attched to node=node.right //its parent else { tmp=node.left; while (tmp.right!= null ) tmp=tmp.right; //find the rightmost node of the left subtree tem.right=node.right; //establish the link between the rightmost node of the left subtree and the right subtree node=node.left; } if (p==root) { root=node; } else if (prev.left==p) { prev.left=node; } else prev.right=node } else if (root!= null ) { System.out.println( "the node is not in the tree" ); } else System.out.println( "The tree is empty" ); } |
希望本文所述對(duì)大家的java程序設(shè)計(jì)有所幫助。