【问题标题】:Search function in Binary Tree Java二叉树Java中的搜索功能
【发布时间】:2014-05-12 23:22:45
【问题描述】:

我正在为我一直从事的项目创建二叉树,我在其中按名称将人员插入二叉树(树遍历每个字符以确定插入时哪个更大)。有没有办法让我的树在树中搜索以找到与程序的名称相匹配的人。这是我目前的代码

lass Node {
private String person;
private Node left;
private Node right;

public Node(String person) {
    this.person = person;
    left = null;
    right = null;
}

//setters
protected void setLeft(Node left) {
    this.left = left;
}

protected void setRight(Node right) {
    this.right = right;
}

//getters
protected String getPerson() {
    return person;
}

protected Node getLeft() {
    return left;
}

protected Node getRight() {
    return right;
}
}

public class BinaryTree {
private static Node root; 

public BinaryTree() {
    root = null;
}

public void insert(String person) {
    root = insert(person, root);
}

//Check if node is leaf
public static boolean isLeaf() {
    if(root.getLeft() == null && root.getRight() == null)
        return false;
    else
        return true;
}

// Search tree for entered value

public static void searchTree(String search, Node tNode) {
// Not sure what to put into the part to make the method search through people in the tree
    }

    private Node insert(String person, Node tree) {
    if(tree == null)
        tree = new Node(person);
    else {
        int count = 1;
        int x = 0;
        while(person.toLowerCase().charAt(x) == tree.getPerson().toLowerCase().charAt(x) && count != tree.getPerson().length()) {
            count = count + 1;
            x = x + 1;
        }
        if(person.toLowerCase().charAt(x) != tree.getPerson().toLowerCase().charAt(x)) {
            if(person.toLowerCase().charAt(x) < tree.getPerson().toLowerCase().charAt(x))
                tree.setLeft(insert(person, tree.getLeft()));
            else
                tree.setRight(insert(person, tree.getRight()));
        } else {
            tree.setRight(insert(person, tree.getRight()));
        }
    }
    return tree;

}

您能否建议我应该如何创建一种搜索树的方法

【问题讨论】:

    标签: java search tree binary-tree binary-search-tree


    【解决方案1】:

    我建议您执行这些步骤。这些步骤将为您提供一个开始。

    1. 从根开始,使用 compareToIgnoreCase() 将要搜索的名称与根进行比较。
    2. 根据结果向左或向右移动。
    3. 继续直到任一节点变为空或找到匹配项。

    【讨论】:

    • 我同意@maus,这个方法每次都需要调用。
    【解决方案2】:

    如果您尝试实现二叉搜索树,则需要更改 setter 中的代码,以确定每次调用这些方法时是将人员添加到左侧节点还是右侧节点(通过按字典顺序比较字符串) .如果树没有排序,则必须搜索每个节点。订购后,您将能够在 log n 时间搜索。

    【讨论】:

    • 其中的insert方法在添加时将它们按列表中的顺序排序
    • 那么搜索有效吗?另外我认为使用 compareTo 或 compareToIgnoreCase 会更容易。
    • 不,搜索不起作用,但现在我正在使用 compareTo 函数,它很好地进行了
    • 好的,让我知道进展如何,我认为你走在正确的轨道上。
    猜你喜欢
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多