原文转载http://blog.sina.com.cn/s/blog_937cbcc10101dmqm.html
二叉查找树
-
- static
class BinaryNode - {
-
T data; -
BinaryNode left; -
BinaryNode right; -
public BinaryNode(T data) { -
this(data,null,null); -
} -
public BinaryNode( T data, BinaryNode left, BinaryNode right) { -
this.data =data; -
this.left = left; -
this.right =right; -
} -
public BinaryNode() -
{ -
data =null; -
this.left = left; -
this.right =right; -
} - }
查找操作
-
-
public boolean contains(T t) -
{ -
return contains(t, rootTree); -
-
} -
-
public boolean contains(T t, BinaryNode node) -
{ -
if(node==null) -
return false;//结点为空,查找失败 -
int result = t.compareTo(node.data); -
if(result>0) -
return contains(t,node.right);//递归查询右子树 -
else if(result<</SPAN>0) -
return contains(t, node.left);//递归查询左子树 -
else -
return true; -
} -
-
-
-
-
public T findMin() -
{ -
if(isEmpty()) -
{ -
System.out.println("二叉树为空"); -
return null; -
}else -
return findMin(rootTree).data; -
-
} -
-
public T findMax() -
{ -
if(isEmpty()) -
{ -
System.out.println("二叉树为空"); -
return null; -
}else -
return findMax(rootTree).data; -
} -
-
-
public BinaryNode findMin(BinaryNode node) -
{ -
if(node==null) -
return null; -
else if(node.left==null) -
return node; -
return findMin(node.left);//递归查找 -
} -
-
public BinaryNode findMax(BinaryNode node) -
{ -
if(node!=null) -
{ -
while(node.right!=null) -
node=node.right; -
} -
return node; -
}
插入操作
-
-
public void insert(T t) -
{ -
rootTree = insert(t, rootTree); -
} -
-
public BinaryNode insert(T t,BinaryNode node) -
{ -
if(node==null) -
{ -
//新构造一个二叉查找树 -
return new BinaryNode(t, null, null); -
} -
int result = t.compareTo(node.data); -
if(result<</SPAN>0) -
node.left= insert(t,node.left); -
else if(result>0) -
node.right= insert(t,node.right); -
else -
;//doNothing -
return node; -
}
删除操作
-
-
public void remove(T t) -
{ -
rootTree = remove(t,rootTree); -
} -
public BinaryNode remove(T t,BinaryNode node) -
{ -
if(node == null) -
return node;//没有找到,doNothing -
int result = t.compareTo(node.data); -
if(result>0) -
node.right = remove(t,node.right); -
else if(result<</SPAN>0) -
node.left = remove(t,node.left); -
else if(node.left!=null&&node.right!=null) -
{ -
node.data = findMin(node.right).data; -
node.right = remove(node.data,node.right); -
} -
else -
node = (node.left!=null)?node.left:node.right; -
return node; -
-
}