package wan;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ExThree {
private double value;
private ExThree left;
private ExThree right;
public ExThree(double value){
this.value=value;
this.left=null;
this.right=null;
}
public void add(ExThree n) {
if(n.getValue()>this.value) {
if(this.getRight()==null) {
this.right=n;
}else{
right.add(n);
}
}
if(n.getValue()<this.value) {
if(this.left==null) {
this.left=n;
}else {
left.add(n);
}
}
}
public List<ExThree> zView(){//中序遍历
List<ExThree> list=new ArrayList<>();
list=bl(list);
return list;
}
private List<ExThree> bl(List<ExThree> list) {
if(this.left!=null) {
left.bl(list);
}
list.add(this);
if(this.right!=null) {
right.bl(list);
}
return list;
}
public void qview(List<ExThree> list) {//前序遍历
list.add(this);
if(this.left!=null) {
left.qview(list);
}
if(this.right!=null) {
right.qview(list);
}
}
public void h(List<ExThree> list) {//后序遍历
if(this.left!=null) {
left.h(list);
}
if(this.right!=null) {right.h(list);}
list.add(this);
}
public ExThree find(double v) {//find node
if(v==value) {
return this;
}
if(v<this.value) {
return left.find(v);
}
if(v>this.value) {
return right.find(v);
}
return null;
}
public static void main(String [] args) {
///根节点
ExThree root=new ExThree(5);
//造树
for(int i=1;i<11;i++) {
ExThree node=new ExThree(i);
if(i==5) {continue;}
root.add(node);
}
System.out.println("中序遍历:");
for(ExThree e:root.zView()) {
System.out.print(e.value+"=>");
}
System.out.println();
System.out.println("前序遍历:");
List<ExThree> list=new ArrayList<>();
root.qview(list);
for(ExThree e2:list) {
System.out.print(e2.value+"=>");
}
System.out.println();
System.out.println("后序遍历:");
List<ExThree> list2=new ArrayList<>();
root.h(list2);
for(ExThree e3:list2) {
System.out.print(e3.value+"=>");}System.out.println();
double nv=5;
System.out.println("请输入查找的节点值:");
Scanner scanner=new Scanner(System.in);
nv=scanner.nextDouble();
System.out.println("value为"+nv+"的节点的儿子:");
if(root.find(nv).getLeft()!=null) {
System.out.println(root.find(nv).getLeft().getValue());
}else {
System.out.println("无");
}
System.out.println("value为"+nv+"的节点的女儿:");
if(root.find(nv).getRight()!=null) {
System.out.println(root.find(nv).getRight().getValue());
}else {
System.out.println("无");
}
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
public ExThree getLeft() {
return left;
}
public void setLeft(ExThree left) {
this.left = left;
}
public ExThree getRight() {
return right;
}
public void setRight(ExThree right) {
this.right = right;
}
}