首先创建一个节点的类,实现Comparable<T>接口
public class Node implements Comparable<Node> { public Object data; public Node left; public Node right; public Node(Object d) { this.data = d; } @Override public int compareTo(Node o) { return (Integer) this.data-(Integer)o.data; } }
自定义一个二叉树的类,包含contians方法和insert方法
public class BInarySearchTree<T extends Comparable<T>> { public Node root; public boolean contains(T i){ if (root==null){ return false; } Node current =root; while (true){ if (current==null){ return false; } if (i.compareTo((T)current.data)==0){ return true; }else if(i.compareTo((T) current.data) < 0){ current = current.left; }else { current = current.right; } } } public boolean insert(T i) { if (root == null) { root = new Node(i); return true; } Node current = root; while (true) { // 如果 i 比当前结点的值小 if (i.compareTo((T) current.data) < 0) { if (current.left != null) { current = current.left; } else { current.left = new Node(i); break; } } else { if (current.right != null) current = current.right; else { current.right = new Node(i); break; } } } return true; } }
定义一个测试类进行测试
public class Test { public static void main(String[] args) { BInarySearchTree<Node> bst=new BInarySearchTree<>(); Node a1=new Node(1); Node a2=new Node(5); Node a3=new Node(7); Node a4=new Node(2); Node a5=new Node(3); bst.insert(a1); bst.insert(a2); bst.insert(a3); bst.insert(a4); bst.insert(a5); System.out.println(bst.contains(new Node(5))); } }
