【问题标题】:Binary Tree Search for non key value二叉树搜索非键值
【发布时间】:2021-06-30 19:18:37
【问题描述】:

我目前正在寻找一种递归算法来在我的树中找到一个非键值。

我有我的节点类:

public class TreeNode {
    private Person person;
    private TreeNode left, right;

    public TreeNode(Person person) {
        this.person = person;
    }

    public boolean insert(Person person) {
        if (person.getAge() < this.person.getAge()){
            if (left != null){
                return left.insert(person);
            }else {
                left = new TreeNode(person);
            }
        }else{
            if (right != null){
                return right.insert(person);
            }else{
                right = new TreeNode(person);
            }
        }
        return true;
    }

    public boolean countryExists(String country){
        if (!this.person.getCountry().equals(country)){
            if (right != null) {
                return right.countryExists(country);
            }
            if (left != null) {
                return left.countryExists(country);
            }
        }else {
            return true;
        }
    }
}

这里的关键值是一个人的年龄。我想知道是否有来自特定国家的人。因此我创建了函数 countryExists(String country) 我不知道如何实现它,我到处搜索并观看了很多关于 post/pre/inorder 的视频。下单应该没问题吧?我在返回正确的布尔值时遇到问题...

感谢您的帮助。

【问题讨论】:

    标签: java tree binary-search-tree


    【解决方案1】:

    在您的countryExists 方法中,您应该在两次!= null 检查后返回false,因为如果执行到这一点,则意味着您的节点没有左右兄弟姐妹(它是叶子)并且它是人的国家不等于您要查找的国家/地区。

    但我建议进行一些重构,而不是否定this.person.getCountry().equals(country),只需使用它并在方法的开头返回true

    public boolean countryExists(String country) {
        if (this.person.getCountry().equals(country)) {
            return true;
        }
    
        if (right != null) {
            return right.countryExists(country);
        }
        if (left != null) {
            return left.countryExists(country);
        }
    
        return false;
    }
    

    另外,这是O(n) 解决方案,因为您没有使用钥匙来切断整个分支,而是进行全树遍历。

    要使其成为O(log n)(在树平衡的情况下),您需要使用country作为key,并且在搜索时只选择一个分支。

    【讨论】:

    • 谢谢!但是有了这个解决方案,我就陷入了右外子树。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2020-12-09
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多