java使用歸并刪除法刪除二叉樹中節(jié)點的方法
本文實例講述了java使用歸并刪除法刪除二叉樹中節(jié)點的方法。分享給大家供大家參考。具體分析如下:
實現(xiàn)的思想很簡單:
first:找到要刪除的節(jié)點
second:如果刪除的節(jié)點沒有右子樹那么左子樹鏈到父節(jié)點
third:如果刪除的節(jié)點沒有左子樹那么右子樹鏈到父節(jié)點
forth:如果刪除的節(jié)點又左右孩子,那么可以歸并刪除節(jié)點后的子樹:方法有兩種一種是用刪除節(jié)點的左子樹的最右節(jié)點,指向刪除節(jié)點的右子樹,另一種是用刪除節(jié)點的用字數(shù)的最左節(jié)點指向刪除節(jié)點的左子樹。
Java 實現(xiàn)如下:
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"); }
希望本文所述對大家的java程序設計有所幫助。
相關文章
解決springboot錯誤:找不到或無法加載主類(配置編碼或者Maven)
這篇文章主要介紹了解決springboot錯誤:找不到或無法加載主類(配置編碼或者Maven)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06