a binary search tree (BST ), which may sometimes also be called an ordered or sorted binary tree , is a node-based binary tree data structure which has the following properties:
Generally, the information represented by each node is a record rather than a single data element. However, for sequencing purposes, nodes are compared according to their keys rather than any part of their associated records.
The major advantage of binary search trees over other data structures is that the related sorting algorithms and search algorithms such as in-order traversal can be very efficient.
Binary search trees are a fundamental data structure used to construct more abstract data structures such as sets , multisets , and associative arrays .
Implements in Java.
Tree Node:
BSTree:
public class BSTree<T extends Comparable<T>> { private Node<T> root = null; public BSTree(){} public Node<T> getRoot() { return root; } public boolean insert(T value){ if(value == null){ return false; } if(root==null){ root = new Node<T>(value); return true; }else{ return BSTInsert(root,value); } } private boolean BSTInsert(Node<T> node,T value){ int result = node.key.compareTo(value); if(result == 0){ throw new RuntimeException("the value has already existed"); }else if(result >0){ if(node.lchild==null){ node.lchild = new Node<T>(value); node.lchild.parent = node; return true; }else{ return BSTInsert(node.lchild, value); } }else{ if(node.rchild==null){ node.rchild = new Node<T>(value); node.rchild.parent = node; return true; }else{ return BSTInsert(node.rchild, value); } } } public boolean search(T value){ if(value==null||root==null){ return false; } return (BSTSearch(root,value)==null); } private Node<T> BSTSearch(Node<T> node, T value){ int result = node.key.compareTo(value); if(result == 0){ return node; }else if(result >0){ return BSTSearch(node.lchild,value); }else{ return BSTSearch(node.rchild,value); } } public boolean delete(T value){ if(root==null||value == null){ return false; } Node<T> delNode = BSTSearch(root, value); if(delNode == null){ return false; } Node<T> parent = delNode.parent; if(delNode.rchild==null){ if(parent.lchild.key == value){ parent.lchild = delNode.lchild; }else{ parent.rchild = delNode.lchild; } return true; } if(delNode.lchild==null){ if(parent.lchild.key == value){ parent.lchild = delNode.rchild; }else{ parent.rchild = delNode.rchild; } return true; } // if either the left child nor the right child is null Node<T> p = delNode; Node<T> s = delNode.lchild; // find the most right node of s, and p is the parent of s while(s.rchild!=null){ p = s; s = s.rchild; } //replace the value of delNode with the value of s delNode.key = s.key; //rebuild the left child if(p!=delNode){ p.rchild = s.lchild; }else{ p.lchild = s.lchild; } s.lchild.parent = p; s.parent = null; s.lchild = null; return true; } }