//
Implements the following functions
public class Binarysearchtree {/** * * @author Administrator * Nested class construction node * @param <Integer> */private static class Bin Arynode<integer>{public Integer data;public binarynode<integer> lchild;public BinaryNode<Integer> Rchild;public Binarynode (Integer d,binarynode<integer> l,binarynode<integer> r) {this.data = D; This.lchild = L;this.rchild = r;}} Root node private binarynode<integer> root;public Binarysearchtree () {root = null;} /** * Returns the root node * @param x * @param r * @return */public binarynode<integer> Add (Integer x,binarynode<integer> R) { binarynode<integer> tmp = r; binarynode<integer> p = new binarynode<integer> (x,null,null); if (TMP = = null) {TMP = P;} Else{while (tmp.lchild!=p && tmp.rchild! = p) {if (x<tmp.data) {if (Tmp.lchild = = null) {tmp.lchild = P;} Else{tmp = Tmp.lchild;} }else if (x>tmp.data) {if (Tmp.rchild = = null) {tmp.rchild = P;} Else{tmp = Tmp.rchild;}}} return r;} /** * Returns the smallest node * @param r * @return */public BinarYnode<integer> Findmin (binarynode<integer> R) {if (r! = null) {while (r.lchild! = null) {R = R.lchild;}} return r;} /** * Returns the maximum node * @param r * @return */public binarynode<integer> Findmax (binarynode<integer> R) {if (r! = null) {W Hile (R.rchild! = null) {R = R.rchild;}} return r;} Delete a node public binarynode<integer> remove (Integer x,binarynode<integer> R) {binarynode<integer> TMP = R; Binarynode<integer> p = null;//indicates the target node's father if (TMP = = null) {throw new NullPointerException ();} while (Tmp.data! = x) {if (x<tmp.data) {p = tmp;tmp = Tmp.lchild;} else if (x<tmp.data) {p = tmp;tmp = Tmp.rchild;}} If the node to be deleted is a leaf node if (tmp.lchild = = NULL && Tmp.rchild = = null) {if (TMP = = r) {TMP = NULL;//If it is the root node, the root node is empty}else if (p.lchild = = tmp) {p.lchild = null;} Else{p.rchild = null;}} else//if for single leaf node if (tmp.lchild = = NULL | | tmp.rchild = = NULL) {if (TMP = = r) {if (Tmp.lchild = = null) {TMP = Tmp.rchild;} else if (Tmp.rchild = = null) {TMP = Tmp.lchild;}} ElseIf (P.lchild = = tmp) {if (Tmp.lchild = = NULL) {p.lchild = Tmp.rchild;} else if (Tmp.rchild = = null) {p.lchild = Tmp.lchild;}} else if (P.rchild = = tmp) {if (Tmp.lchild = = null) {p.lchild = Tmp.rchild;} else if (Tmp.rchild = = null) {p.lchild = Tmp.lchild;}}} else {//the sub-nodes of the target node are not empty binarynode<integer> a = tmp; binarynode<integer> B = tmp.rchild; while (b.lchild! = null) {//Select the least right number of data A = B;b = B.lchild;} Tmp.data = b.data;if (A = = tmp) {tmp.rchild = b.rchild;//if the right sub-node of the target node has no left child nodes}else{a.lchild = B.rchild;}} return r;}}
Java: Two-fork search tree for non-recursive methods to implement some functions