Java using merge deletion method to remove nodes in binary tree _java

Source: Internet
Author: User
Tags prev

This article illustrates the Java method of deleting nodes in a binary tree using the merge deletion method. Share to everyone for your reference. The specific analysis is as follows:

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 B
E deleted*/while (P!=null&&p.key!=el) {prev=p; if (P.key<el) p=p.right; else p=p.left;}/*find end*/; if (P!=null&&p.key==el) {if (node.right==null)//node has no right child then it left child (if all) is attached T
o Node=node.left; Its parent else if (node.left==null)//node has no left child then it right child (if any) are 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) {Sys
TEM.OUT.PRINTLN ("The node isn't in");
Else System.out.println ("The Tree is empty"); }

I hope this article will help you with your Java programming.

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.