public class BinarySortTree {
private Node treeNode;
private int size;
public int getSize ( ) {
return size;
}
public void add ( int item) {
if ( treeNode== null) {
treeNode= new Node ( item) ;
size++ ;
} else {
boolean b= treeNode. addChild ( item) ;
if ( b) {
size++ ;
}
}
}
public void searchAll ( ) {
if ( treeNode== null) {
System. out. println ( "没有元素" ) ;
} else {
treeNode. printNode ( ) ;
}
}
static class Node {
private int item;
private Node left;
private Node right;
public Node ( int item) {
this . item = item;
}
public boolean addChild ( int item) {
if ( this . item> item) {
if ( this . left== null) {
System. out. println ( item+ "在" + this . item+ "的左侧" ) ;
this . left= new Node ( item) ;
return true ;
} else {
return this . left. addChild ( item) ;
}
} else if ( this . item< item) {
if ( this . right== null) {
System. out. println ( item+ "在" + this . item+ "的右侧" ) ;
this . right= new Node ( item) ;
return true ;
} else {
return this . right. addChild ( item) ;
}
} else {
System. out. println ( "重复元素" ) ;
}
return false ;
}
public void printNode ( ) {
if ( this . left!= null) {
this . left. printNode ( ) ;
}
System. out. println ( this . item) ;
if ( this . right!= null) {
this . right. printNode ( ) ;
}
}
}
}
public class TestTree {
public static void main ( String[ ] args) {
BinarySortTree binarySortTree= new BinarySortTree ( ) ;
binarySortTree. add ( 10 ) ;
binarySortTree. add ( 13 ) ;
binarySortTree. add ( 16 ) ;
binarySortTree. add ( 17 ) ;
binarySortTree. add ( 17 ) ;
binarySortTree. add ( 17 ) ;
System. out. println ( binarySortTree. getSize ( ) ) ;
binarySortTree. searchAll ( ) ;
}
}