public class BinaryTree {
Node root;
public void setRoot(Node root) {
this.root = root;
}
public Node getRoot() {
return root;
}
public void frontShow() {
if(root!=null) {
root.frontShow();
}
}
public void midShow() {
if(root!=null) {
root.midShow();
}
}
public void afterShow() {
if(root!=null) {
root.afterShow();
}
}
public Node frontSearch(int i) {
return root.frontSearch(i);
}
public void delete(int i) {
if(root.value==i) {
root=null;
}else {
root.delete(i);
}
}
}
public class Node {
int value;
Node leftNode;
Node rightNode;
public Node(int value) {
this.value=value;
}
public void setLeftNode(Node leftNode) {
this.leftNode = leftNode;
}
public void setRightNode(Node rightNode) {
this.rightNode = rightNode;
}
public void frontShow() {
System.out.println(value);
if(leftNode!=null) {
leftNode.frontShow();
}
if(rightNode!=null) {
rightNode.frontShow();
}
}
public void midShow() {
if(leftNode!=null) {
leftNode.midShow();
}
System.out.println(value);
if(rightNode!=null) {
rightNode.midShow();
}
}
public void afterShow() {
if(leftNode!=null) {
leftNode.afterShow();
}
if(rightNode!=null) {
rightNode.afterShow();
}
System.out.println(value);
}
public Node frontSearch(int i) {
Node target=null;
if(this.value==i) {
return this;
}else {
if(leftNode!=null) {
target = leftNode.frontSearch(i);
}
if(target!=null) {
return target;
}
if(rightNode!=null) {
target=rightNode.frontSearch(i);
}
}
return target;
}
public void delete(int i) {
Node parent = this;
if(parent.leftNode!=null&&parent.leftNode.value==i) {
parent.leftNode=null;
return;
}
if(parent.rightNode!=null&&parent.rightNode.value==i) {
parent.rightNode=null;
return;
}
parent=leftNode;
if(parent!=null) {
parent.delete(i);
}
parent=rightNode;
if(parent!=null) {
parent.delete(i);
}
}
}
public class TestBinaryTree {
public static void main(String[] args) {
BinaryTree binTree = new BinaryTree();
Node root = new Node(1);
binTree.setRoot(root);
Node rootL = new Node(2);
root.setLeftNode(rootL);
Node rootR = new Node(3);
root.setRightNode(rootR);
rootL.setLeftNode(new Node(4));
rootL.setRightNode(new Node(5));
rootR.setLeftNode(new Node(6));
rootR.setRightNode(new Node(7));
binTree.frontShow();
System.out.println("===============");
binTree.midShow();
System.out.println("===============");
binTree.afterShow();
System.out.println("===============");
Node result = binTree.frontSearch(5);
System.out.println(result);
System.out.println("===============");
binTree.delete(4);
binTree.frontShow();
}
}