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.