class BinarySortTree
package DataStructures.tree;
public class BinarySortTree {
public static void main(String[] args) {
int[] arr = {7,3,10,12,5,1,9,2};
BinarySortTree binarySortTree = new BinarySortTree();
for (int i = 0; i < arr.length; i++) {
binarySortTree.add(new Node2(arr[i]));
}
binarySortTree.delNode(10);
binarySortTree.infixOrder();
}
private Node2 root;
public void delNode(int value){
if (root == null){
return;
}else {
Node2 target = search(value);
if (target == null){
return;
}
if (root.left == null && root.right == null){
root = null;
return;
}
Node2 parent = searchParent(value);
if (target.left == null && target.right == null) {
if (parent.left != null && target == parent.left) {
parent.left = null;
} else if (parent.right != null && target == parent.right) {
parent.right = null;
}
}else if (target.left == null || target.right == null){
if (target.right == null){
if (parent == null){
root = target.left;
}
if (target == parent.left){
parent.left = target.left;
}else {
parent.right = target.left;
}
}else{
if (parent == null){
root = target.right;
}
if (target == parent.left){
parent.left = target.right;
}else {
parent.right = target.right;
}
}
} else {
target.value = delRightTreeMin(target.right);
}
}
}
public int delRightTreeMin(Node2 node){
while (node.left != null){
node = node.left;
}
delNode(node.value);
return node.value;
}
public Node2 searchParent(int value) {
return root.searchParent(value);
}
public Node2 search(int value){
return root.search(value);
}
public void add(Node2 node){
if (root == null){
root = node;
}else {
root.add(node);
}
}
public void infixOrder(){
if (root != null){
root.infixOrder();
}else {
System.out.println("空,不可遍历");
}
}
}
class Node2{
int value;
Node2 left;
Node2 right;
public Node2(int value) {
this.value = value;
}
@Override
public String toString() {
return "Node2{" +
"value=" + value +
'}';
}
public Node2 searchParent(int value) {
if ((this.left != null && this.left.value == value) || (this.right != null && this.right.value == value)) {
return this;
} else {
if (value < this.left.value && this.left != null) {
return this.left.searchParent(value);
} else if (value >= this.right.value && this.right != null){
return this.right.searchParent(value);
}else {
return null;
}
}
}
public Node2 search(int value){
if (this.value == value){
return this;
}else if (value < this.value){
if (this.left == null){
return null;
}
return this.left.search(value);
}else {
if (this.right == null){
return null;
}
return this.right.search(value);
}
}
public void add(Node2 node){
if (node == null){
return;
}
if (node.value < this.value){
if (this.left == null){
this.left = node;
}else {
this.left.add(node);
}
}else {
if (this.right == null){
this.right = node;
}else {
this.right.add(node);
}
}
}
public void infixOrder(){
if (this.left != null){
this.left.infixOrder();
}
System.out.println(this);
if (this.right != null){
this.right.infixOrder();
}
}
}