二叉查找树
二叉查找树,又称二叉排序树,具有如下性质
- 若它的左子树不为空,则左子树上所有
- 结点的值均小于它的根结构的值
- 若它的右子树不为空,则右子树上所有结点的值均大于它的根结点的值
- 它的左、右子树也分别为二叉排序树
//树的结点类
public class TreeNode<T> {
//存储数据
public T data;
//指向左孩子和右孩子结点
public TreeNode<T> left,right;
public TreeNode(T data, TreeNode<T> left, TreeNode<T> right) {
super();
this.data = data;
this.left = left;
this.right = right;
}
public TreeNode(T data) {
super();
this.data = data;
}
public TreeNode() {
this.data = null;
this.left = null;
this.right =null;
}
public String toString() {
return this.data.toString();
}
}
//我们使用泛型保证传入的对象必须具有比较的性质
public class BinarySearchTree<T extends Comparable> {
public TreeNode<T> root;
public BinarySearchTree() {
super();
}
public BinarySearchTree(T x) {
super();
root=new TreeNode<>(x);
}
//判断该树是否为空
public boolean isEmpty() {
return root==null;
}
public boolean contains(T x) {
return contains(x,root);
}
//判断当前树是否包含某个对象,对象必须实现Comparable接口或者手动实现比较器,使用递归来完成
public boolean contains(T x,TreeNode<T> root) {
if(root==null) {
return false;
}
int result=x.compareTo(root.data);
if(result<0) {
return contains(x,root.left);
}else if(result >0) {
return contains(x,root.right);
}else{
return true;
}
}
public T findMax() {
return findMax(root);
}
//查找最大值
public T findMax(TreeNode<T> root)
{
if(root==null) {
return null;
}else if(root.right==null) {
return root