源代码
package BinarySortTree;
public class BinarySortTreeDemo {
public static void main(String[] args) {
int[] arr = {7, 3, 10, 12, 5, 1, 9};
BinarySortTree binarySortTree = new BinarySortTree();
for(int i = 0; i < arr.length; i++) {
binarySortTree.add(new Node(arr[i]));
}
System.out.println("删除前:");
binarySortTree.infixOrder();
binarySortTree.delNode(9);
System.out.println("删除后:");
binarySortTree.infixOrder();
}
}
class BinarySortTree{
private Node root;
public void add(Node node) {
if(root == null) {
root = node;
}else {
root.add(node);
}
}
public Node search(int value) {
if(root == null) {
return null;
}else {
return root.search(value);
}
}
public Node searchParent(int value) {
if(root == null) {
return null;
}else {
return root.searchParent(value);
}
}
public void delNode(int value) {
if(root == null) {
return;
}else {
Node target = search(value);
if(target == null) {
return;
}
if(root.getLeft() == null && root.getRight() == null) {
root = null;
return;
}
Node parent = searchParent(value);
if(target.getLeft() == null && target.getRight() == null) {
if(parent.getLeft() != null && parent.getLeft().getValue() == value) {
parent.setLeft(null);
}else if (parent.getRight() != null && parent.getRight().getValue() == value) {
parent.setRight(null);
}
}
}
}
public void infixOrder() {
if(root != null) {
root.infixOrder();
}else {
System.out.println("这是一棵空树!");
}
}
}
class Node{
private int value;
private Node left;
private Node right;
public Node(int value) {
this.value = value;
}
public Node search(int value) {
if(value == this.value) {
return this;
}else if (value < this.value) {
if(this.getLeft() == null) {
return null;
}
return this.getLeft().search(value);
}else {
if(this.getRight() == null) {
return null;
}
return this.getRight().search(value);
}
}
public Node searchParent(int value) {
if((this.getLeft() != null && this.getLeft().value == value) ||
(this.getRight() != null && this.getRight().value == value))
{
return this;
}else {
if (this.getLeft() != null && value < this.getValue()) {
return this.getLeft().searchParent(value);
}else if(this.getRight() != null && value >= this.getValue()){
return this.getRight().searchParent(value);
}else {
return null;
}
}
}
public void add(Node node) {
if(node.getValue() < this.getValue()) {
if(this.getLeft() == null) {
this.setLeft(node);
}else {
this.getLeft().add(node);
}
}else {
if(this.getRight() == null) {
this.setRight(node);
}else {
this.getRight().add(node);
}
}
}
public void infixOrder() {
if(this.getLeft() != null) {
this.getLeft().infixOrder();
}
System.out.println(this);
if(this.getRight() != null) {
this.getRight().infixOrder();
}
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
@Override
public String toString() {
return "Node [value=" + value + "]";
}
}