删除二叉树中的节点——归并删除法

实现的思想很简单:

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 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");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值