2012-03-21 147 views
0

我创建了一个BST,它将每个节点设置为一个字符串值,我想知道是否有一种方法可以在树中搜索,但一次只能搜索一个值。所以说节点中的字符串是“卡车”,有没有办法在树中搜索并返回“t”?这是我的代码具有兴建树:通过BST搜索

public class BinaryTree { 

public Node root; 
public BinaryTree tree; 
public static int pos; 
public static Node[] theArray; 

private static class Node { 
    Node left; 
    Node right; 
    String data; 

    Node(String s) { 
     left = null; 
     right = null; 
     data = s; 
    } 
} 

public BinaryTree plantTree(ArrayList<String> dict) { 

    tree = new BinaryTree(); 

    Collections.shuffle(dict); 

    for (String s : dict) { 
     s.toUpperCase(); 
     tree.add(s); 
    } 

    return tree; 

} 

/** 
* Creates an empty binary tree 
*/ 
public BinaryTree() { 
    root = null; 
} 

public void add(String data) { 
    root = add(root, data); 
} 

private Node add(Node node, String data) { 
    if (node == null) { 
     node = new Node(data); 
    } else { 
     if (data.compareTo(node.data) > 0) { 
      node.left = add(node.left, data); 
     } else { 
      node.right = add(node.right, data); 
     } 
    } 

    return (node); 
} 

}

+1

你的问题不清楚 – Adrian 2012-03-21 20:37:55

回答

1

也许我误解了你的问题,但它听起来像你想要的东西遍历树。我会使用访问者模式。 (这听起来像是功课,所以为什么不使用标准模式:))

public class Node<T>{ 
... 
    public void visitDepthFirst(Visitor<T> v){ 
     v.visit(this); 
     if (left != null){ 
      left.visitDepthFirst(v); 
     } 
     if (right != null){ 
      right.visitDepthFirst(v); 
     } 
    } 
} 

interface Visitor<T>{ 
    public void visit(T t); 
} 
... 
Node<String> root = ...; 
root.visitDepthFirst(new Visitor<String>(){ 
    public visit(String val){ 
     if ("truck".equals(val)){ 
      // do something 
     } 
    } 
}); 

我会让你找出广度搜索。此外,使用泛型的节点类将更加有用。而你的班级结构有点混乱。我建议你只使用节点AS树本身。毕竟,树中的每个节点都是树本身。 (阅读有关复合模式)

0

这样看来,你试图通过仅第一个字母,通过你的树进行搜索。这只要返回整个单词就可以了。所以你仍然需要使用BST遍历或搜索算法。

0

所以说,在一个节点的字符串是“卡车”有没有办法来搜索 通过树,并返回“T”?

真的,我不知道这个问题是关于什么。
如果您有BST,那么您可以使用二分搜索进行搜索。就是这样。

如果找到该元素,则二分查找返回true。如果值不是树的一部分,您可以实现自己的BST,不返回boolean,而是返回Char,如t中的问题,null