国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java使用歸并刪除法刪除二叉樹中節點的方法

2019-11-26 15:10:26
字體:
來源:轉載
供稿:網友

本文實例講述了java使用歸并刪除法刪除二叉樹中節點的方法。分享給大家供大家參考。具體分析如下:

實現的思想很簡單:

first:找到要刪除的節點
second:如果刪除的節點沒有右子樹那么左子樹鏈到父節點
third:如果刪除的節點沒有左子樹那么右子樹鏈到父節點
forth:如果刪除的節點又左右孩子,那么可以歸并刪除節點后的子樹:方法有兩種一種是用刪除節點的左子樹的最右節點,指向刪除節點的右子樹,另一種是用刪除節點的用字數的最左節點指向刪除節點的左子樹。

Java 實現如下:

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 parentelse{tmp=node.left;  while(tmp.right!=null)tmp=tmp.right;//find the rightmost node of the left subtreetem.right=node.right;//establish the link between the rightmost node of the left subtree and the right subtreenode=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程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 寻乌县| 汉中市| 和硕县| 甘德县| 温宿县| 开鲁县| 黑龙江省| 宁国市| 武安市| 阳信县| 平江县| 武川县| 韶山市| 遂溪县| 惠来县| 资溪县| 哈密市| 和田县| 兴安县| 盐边县| 明光市| 蒲城县| 白玉县| 梅河口市| 崇州市| 漾濞| 洪湖市| 息烽县| 旬邑县| 武安市| 普定县| 六安市| 金湖县| 正蓝旗| 海晏县| 平和县| 社旗县| 大理市| 环江| 临武县| 余庆县|