我有這個東西比較不與二叉樹工作
Comparator.java
public interface Comparator<T> {
public int compareTo(int num);
}
valueComparator.java
public class valueComparator implements Comparator<Tree.Node> {
@Override
public int compareTo(Tree.Node obj, int number) {
if (obj.getDataNumber() == number) {
return 0;
}
else if (obj.getDataNumber() < number) {
return -1;
}
else return 1;
}
}
Tree.java
public class Tree {
public Node root;
Tree() {
}
public static class Node {
Node(int number, String str, boolean flag) {
dataNumber = number;
dataText = str;
dataBool = flag;
}
public int getDataNumber() {
return this.dataNumber;
}
public String getDataText() {
return this.dataText;
}
public boolean getDataBool() {
return this.dataBool;
}
public void setDataText(String text) {
this.dataText = text;
}
public void isDataBool(boolean flag) {
this.dataBool = flag;
}
Node left;
Node right;
private int dataNumber;
private String dataText;
private boolean dataBool;
}
public void binaryTree() {
root = null;
}
public boolean search(int number) {
return search(root, number);
}
valueComparator comp = new valueComparator();
private boolean search(Node node, int number) {
if (node == null) {
return false;
}
if (comp.compareTo(node, number) == 0) {
return true;
}
if (comp.compareTo(node, number) == -1) {
return search(node.left, number);
}
else {
return search(node.right, number);
}
}
public void insertLeaf(int number, String str, boolean flag) {
root = insertLeaf(root, number, str, flag);
}
private Node insertLeaf(Node node, int number, String str, boolean flag) {
if (node == null) {
node = new Node(number, str, flag);
} else {
if (number < node.dataNumber) {
node.left = insertLeaf(node.left, number, str, flag);
}
else if (number > node.dataNumber) {
node.right = insertLeaf(node.right, number, str, flag);
}
else {
System.out.println("The element is already in the tree.");
}
}
return node;
}
}
Test.java
public class Test {
public static void main(String args[]) {
Tree binTree = new Tree();
binTree.binaryTree();
binTree.insertLeaf(5, "text2", true);
binTree.insertLeaf(4, "text4", false);
binTree.insertLeaf(1, "text1", true);
binTree.insertLeaf(3, "text3", true);
binTree.insertLeaf(2, "text5", false);
System.out.println("Element 3 found: " + binTree.search(3));
// Element 3 found: false
}
}
我應該做一個比較搜索,但我不明白的邏輯。 compareTo
方法可以自己工作,但它會搜索遞歸調用。第一遍之後,如果compareTo的返回值不爲0,那麼它將與null
一起輸入並跳出遞歸併返回false。意思是如果我將樹的第一個元素設置爲'3',搜索(3)將返回true,但是如果它不同於3 - false並且甚至不會在樹中查找它。
您可以爲正在使用的編程語言添加標籤嗎? – 2015-04-04 11:29:03
請發佈真正的代碼,編譯。您的比較器無法編譯。 – 2015-04-04 11:38:00
對不起。這只是我第一次在這裏發佈:D – 2015-04-04 11:44:04