//节点类
class Node1{
public Node1 leftchild;//左子节点
public Node1 rightchild;//右子节点
public int data;
public String font;
public Node1(int value,String text){
data=value;
font=text;
}
}
//二叉树
class Tree{
public Node1 root;
public void insert(int value,String text){
Node1 node=new Node1(value,text);
Node1 current =root;
Node1 parent;
if(root==null){
root=node;
}else{
while(true){
parent=current;
if(current.data>value){
current=current.leftchild;
if(current==null){
parent.leftchild=node;
return;
}
}else{
current=current.rightchild;
if(current==null){
parent.rightchild=node;
return;
}
}
}
}
}
//查找
public void find(int value){
Node1 current=root;
while(current.data!=value){
if(current.data>value){
current=current.leftchild;
}else{
current=current.rightchild;
}
if(current==null){
System.out.println("找不到");
}
} System.out.println(current.data);
}
//前序遍历
public void front(Node1 localNode){
if(localNode!=null){
System.out.println(localNode.data+" "+localNode.font);
front(localNode.leftchild);
front(localNode.rightchild);
}
}
//中序遍历
public void middle(Node1 localNode){
if(localNode!=null){
middle(localNode.leftchild);
System.out.println(localNode.data+" "+localNode.font);
middle(localNode.rightchild);
}
}
//后序遍历
public void behind(Node1 localNode){
if(localNode!=null){
behind(localNode.leftchild);
behind(localNode.rightchild);
System.out.println(localNode.data+" "+localNode.font);
}
}
//删除节点
public boolean delete(int value){
Node1 current=root;
Node1 parent=root;
boolean isLeftchild=true;
while(current.data!=value){
parent=current;
if(current.data>value){
current=current.leftchild;
isLeftchild=true;
}else if(current.data<value){
current=current.rightchild;
isLeftchild=false;
}if(current==null){
return false;
}
}
if(current.leftchild==null&¤t.rightchild==null){
if(current==root){
root=null;
}else if(isLeftchild){
parent.leftchild=null;
}else{
parent.rightchild=null;
}
}else if(current.rightchild==null){
if(current==root){
root=current.leftchild;
}else if(isLeftchild){
parent.leftchild=current.leftchild;
}else{
parent.rightchild=current.leftchild;
}
}else if(current.leftchild==null){
if(isLeftchild){
parent.leftchild=current.rightchild;
}else{
parent.rightchild=current.rightchild;
}
}else{
Node1 success=getsuccess(current);
if(current==root){
root=success;
}else if(isLeftchild){
parent.leftchild=success;
}else{
parent.rightchild=success;
}success.leftchild=current.rightchild;
}
return true;
}
public Node1 getsuccess(Node1 delnode){
Node1 successor=delnode;
Node1 successorParent=delnode;
Node1 current=delnode.rightchild;
while(current!=null){
successorParent=successor;
successor=current;
current=current.leftchild;
}
if(successor!=delnode.rightchild){
successorParent.leftchild=successor.rightchild;
successor.rightchild=delnode.rightchild;
}return successor;
}
}