2009/06/10 Datastructure
package ch6;
import java.util.*;
class TreeNode
{
T data;
TreeNode
TreeNode
public TreeNode(T data) { this.data = data; }
public int compareTo(Object o) {
Comparable d1 = (Comparable) data;
Comparable d2 = (Comparable) (((TreeNode
return d1.compareTo(d2);
}
public String toString() { return ""+data; }
}
/**
*
* @author student
*/
public class BinarySearchTree
private TreeNode
public void printTree()
{
printTree(root);
}
private void printTree(TreeNode
{
if (node == null) return;
System.out.println(node);
printTree(node.llink);
printTree(node.rlink);
}
public void postorderTraverse()
{
postorderTraverse(root);
}
private void postorderTraverse(TreeNode
{
if (node == null) return;
postorderTraverse(node.llink);
postorderTraverse(node.rlink);
System.out.print(node.data+" ");
}
public void levelorderTraverse()
{
levelorderTraverse(root);
}
private void levelorderTraverse(TreeNode
{
if (node == null) return;
Queue
queue.add(node);
while (! queue.isEmpty())
{
TreeNode
System.out.print(p.data+" ");
if (p.llink != null) queue.add(p.llink);
if (p.rlink != null) queue.add(p.rlink);
}
}
public BinarySearchTree
{
root=delete(root, data);
return this;
}
private TreeNode
{
TreeNode
if (node == null)
{
System.out.println("Cannot find data="+data+" in this tree.");
return node;
}
if (newnode.compareTo(node) < 0)
node.llink = delete(node.llink, data);
else if (newnode.compareTo(node) > 0)
node.rlink = delete(node.rlink, data);
else // has found!
{
if (node.llink == null)
node = node.rlink;
else if (node.rlink == null)
node = node.llink;
else // both left & right trees are existent
{
TreeNode
node.data = successor.data;
node.rlink = delete(node.rlink, successor.data);
}
}
return node;
}
private TreeNode
{
if (node.llink == null) return node;
return findSuccessor(node.llink);
}
public BinarySearchTree
{
root=insert(root, data);
return this;
}
private TreeNode
{
TreeNode
if (node == null) { node=newnode; return node; }
if (newnode.compareTo(node) < 0) // left tree
node.llink = insert(node.llink, data);
else
node.rlink = insert(node.rlink, data);
return node;
}
}