java树的构造
public class BinearySearchTree<T extends Comparable<T>> {
private class Node{
private T ele;
private Node left,right;
public Node(T e){
this.ele=e;
this.left=this.right=null;
}
}
private Node root;
private int size;
public BinearySearchTree(){
this.root=null;
this.size=0;
}
public int getSize(){
return this.size;
}
public void add(T e){
this.root=addDG(root,e);
this.size++;
}
private Node addDG(Node root,T e){
if(root==null){
return new Node(e);
}
if(root.ele.compareTo(e)>0){
root.left=addDG(root.left,e);
}else{
root.right=addDG(root.right, e);
}
return root;
}
public boolean search(T e){
return searchDG(this.root,e);
}
private boolean searchDG(Node root,T e){
if(root==null){
return false;
}
if(root.ele.compareTo(e)==0){
return true;
}else if(root.ele.compareTo(e)>0){
return searchDG(root.left,e);
}else{
return searchDG(root.right,e);
}
}
public void preTravel(){
List<T> list=new ArrayList<>();
preTravelDG(this.root,list);
System.out.println(list.stream().map(item->item.toString()+"-->").collect(Collectors.joining()));
}
private void preTravelDG(Node root,List<T> list){
if(root==null){
return;
}
list.add(root.ele);
preTravelDG(root.left,list);
preTravelDG(root.right,list);
}
public void midTravel(){
List<T> list=new ArrayList<>();
midTravelDG(this.root,list);
System.out.println(list.stream().map(item->item.toString()+"-->").collect(Collectors.joining()));
}
private void midTravelDG(Node root,List<T> list){
if(root==null){
return;
}
midTravelDG(root.left,list);
list.add(root.ele);
midTravelDG(root.right,list);
}
public void suffixTravel(){
List<T> list=new ArrayList<>();
suffixTravelDG(this.root,list);
System.out.println(list.stream().map(item->item.toString()+"-->").collect(Collectors.joining()));
}
private void suffixTravelDG(Node root,List<T> list){
if(root==null){
return;
}
suffixTravelDG(root.left,list);
suffixTravelDG(root.right,list);
list.add(root.ele);
}
}