Get the App
SLTechnology News&Howtos  ›  Servers  › 

How to delete binary tree in Java

Shulou Source: shulou.com Published: 2022-06-01 18:49:55 09月11日 Update

Java how to achieve binary tree deletion, I believe that many inexperienced people are helpless, this article summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

Binary tree deletion is divided into three cases.

The first type: if it is a leaf node, it can be deleted directly, as shown in Figure 1.

The second type: if there is only left subtree or only right subtree, as long as the left subtree or right subtree is the left subtree or right subtree of its parent node, as shown in Figure 2.

Third: If a node has both left and right nodes, we need to replace it with its predecessor or successor in the in-order sequence, and then delete its predecessor or successor. At this time, the predecessor or successor node of the node must be a node without a right child or a left child. The deletion method can refer to the second method, as shown in Figure 3.

Input: ele element to be deleted

Output: Delete ele in binary search tree

Code:

public Object remove(Object ele){ BinTreeNode v = (BinTreeNode)binTSearch(root,ele);if (v==null) return null; //Search failed BinTreeNode del = null; //Node to be deleted BinTreeNode subT = null; //Subtree of node to be deleted if (! v.hasLChild()||! v.hasRChild()) //determine the node to delete del = v;else{ del = getPredecessor(v); Object old = v.getData(); v.setData(del.getData()); del.setData(old); } startBN = del.getParent(); //Starting point to be balanced *//At this time, the node to be deleted has only left subtree or right subtree if (del.hasLChild()) subT = del.getLChild();elsesubT = del.getRChild();if (del==root) { //If the node to be deleted is root if (subT!= null) subT.sever(); root = subT; } elseif (subT!= null){//del is a non-leaf node if (del.isLChild()) del.getParent().setLChild(subT);else del.getParent().setRChild(subT); }else//del is the leaf node del.sever();return del.getData();} After reading the above content, do you know how to implement binary tree deletion in Java? If you still want to learn more skills or want to know more related content, welcome to pay attention to the industry information channel, thank you for reading!

Tags: Nodes subtrees nodes precursors only leaves methods such as pictures content children more problems helpless for this code elements starting point reason this sequence Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno MySQL Shulou Tech Info Apple NVidia