Delete a node in a binary tree--merge Delete method

Source: Internet
Author: User

The idea of realization is simple:

I: Find the node to delete

Second: If the deleted node does not have a right subtree then the left subtree is linked to the parent node

Third: If the deleted node has no left subtree then the right subtree is linked to the parent node

Forth: If the deleted node is left to the child, then you can merge the subtree after the deletion of the node: there are two kinds of methods is to delete the node in the left subtree of the right subtree, point to delete the node of the right sub-tree, the other is the deletion of the node in the leftmost node of the word point to the deletion of the node's left subtree.

The Java implementation is as follows:

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 it left child (if any) are attached to
Node=node.left; Its parent
else if (node.left==null)//node has no left child then it right child (if all) 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 isn't in");
}
Else System.out.println ("The Tree is empty");
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.