【发布时间】:2015-02-16 08:16:16
【问题描述】:
我正在尝试在 Java 中快速实现二叉搜索树。具有按顺序遍历方法的最佳使用类是什么? (我听说过 TreeMap 类。但看起来该类不包含任何按顺序遍历的方法)。
【问题讨论】:
-
我认为没有任何标准库可用于此。检查此链接以获取示例实现java-tips.org/java-se-tips/java.lang/…
我正在尝试在 Java 中快速实现二叉搜索树。具有按顺序遍历方法的最佳使用类是什么? (我听说过 TreeMap 类。但看起来该类不包含任何按顺序遍历的方法)。
【问题讨论】:
使用LinkedHashMap按插入顺序遍历或TreeMap按比较顺序遍历 http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html
【讨论】:
您总是可以创建自己的类,并使用该类实现算法。
public class Node {
Node leftChild;
Node rightChild;
int parent;
Node(int parent) {
this.parent = parent;
}
}
然后实现二叉搜索树类。这个速度很快,但它是为了给你一个想法。
public class BSTree {
Node root;
BSTree() {
root = null;
}
public void insert(Node node, int value) {
if (value >= node.parent) {
if (!(node.rightChild == null)) {
insert(node.rightChild, value);
} else {
node.rightChild = new Node(value);
}
} else if (value < node.parent) {
if (!(node.leftChild == null)) {
insert(node.leftChild, value);
} else {
node.leftChild = new Node(value);
}
} else {
root = new Node(value);
}
}
public boolean delete(Node node, int value) {
if (root == null) {
return false;
} else if (value > root.parent) {
return delete(root.rightChild, value);
} else if (value < root.parent) {
return delete(root.leftChild, value);
} else {
if (root.leftChild == null && root.rightChild == null) {
root = null;
return true;
} else if (root.leftChild == null && root.rightChild != null) {
root = root.rightChild;
return true;
} else if (root.leftChild != null && root.rightChild == null) {
root = root.leftChild;
return true;
} else {
Node minRight = minNode(root.rightChild);
root = minRight;
delete(minRight, minRight.parent);
return true;
}
}
}
public Node minNode(Node node) {
if (node.leftChild == null) {
return node;
} else {
return minNode(node.leftChild);
}
}
}
【讨论】:
TreeSet 类可能是你想要的
class Node implements Comparable<Node>; // implements your Node class
TreeSet<Node> set = new TreeSet<Node>();
// after adding a bunch of nodes into set
Iterator<Node> it = set.iterator();
while(it.hasNext()){
Node current = it.next();
System.out.println(current); // operate on current node
}
Node first = set.first(); // smallest element in set
Node second = set.ceiling(first); // the successor method
【讨论】: