//建立內部類Node,Node表明的就是樹節點 public static class Node{ int key; Node leftChild; Node rightChild; public Node(int key){ this.key=key; this.leftChild=null; this.rightChild=null; } public Node(int key,Node leftChild,Node rightChild){ this.key=key; this.leftChild=leftChild; this.rightChild=rightChild; } public int getKey(){ return key; } @Override public boolean equals(Object o){ Node node=(Node)o; return getKey() == node.key; } public Node left(){ return this.leftChild; } public Node right(){ return this.rightChild; } }
//成員變量以及構造函數 public Node root; public BinarySearchTree(){ root=null; }
public boolean isEmpty(){ return root == null ? true : false; } public void makeEmpty(){ this.root=null; } public boolean contains(int target,Node node){ if(node == null || isEmpty()){ return false; } if(target<node.key){ return contains(target, node.leftChild); }else if(target>node.key){ return contains(target,node.rightChild); }else{ return true; } } public Node findMin(Node node){ if(node==null || isEmpty()){ return null; } if(node!=null && node.leftChild!=null) { return findMin(node.leftChild); }else{ return node; } } public Node findMax(Node node){ if(node==null || isEmpty()){ return null; } //這就是返回條件(遞歸結束條件) if(node.rightChild == null) return node; return findMax(node.rightChild); } //總體思路就是插入哪個節點,就返回哪個節點 public Node insert(int key,Node node){ if(node==null){ //用於真實生成節點(遞歸結束條件) return new Node(key,null,null); }else if(key < node.key){ //用於創建與左節點間的關聯 node.leftChild=insert(key, node.leftChild); }else if(key > node.key){ //用於創建與右節點間的關聯 node.rightChild=insert(key, node.rightChild); }else ; return node; } public void insert(int key){ root=insert(key,root); } //思路與插入思路差很少,刪除那個節點就返回哪個節點 public Node remove(int key,Node node){ if(node == null) return null; if(key < node.key){ node.leftChild=remove(key, node.leftChild); }else if(key > node.key){ node.rightChild=remove(key, node.rightChild); } //左右子樹均非空 else if(node.leftChild != null && node.rightChild != null){ //找到要移動的節點並替換掉,該過程出現新一輪的樹枝生成過程 node.key=findMin(root.rightChild).key; //這裏負責新樹枝的生成,由於這裏要移動的是該節點的右分支,因此其實永遠不會有刪除動做發生,只會發生一點樹枝的移動動做 node.rightChild=remove(node.key, node.rightChild); } //左子樹或者右子樹爲空,此時node節點即爲要刪除的節點或者不存在的刪除節點 else{ node = (node.rightChild == null) ? node.leftChild : node.rightChild; } return node; } public void remove(int key){ root=remove(key, root); }
以上就簡單介紹了二人查找數的基本操做,固然用的是遞歸實現,可是也能夠用到非遞歸的方法,這裏再也不給出。java