递归搜索树而不传递对象 [英] Recursive search through tree without passing object

查看:42
本文介绍了递归搜索树而不传递对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在非二叉树中搜索节点,而实际上并未将节点传递给搜索方法.

I'm trying to search for a node in a non-binary tree without actually passing a node to the search method.

每个节点都有一个 name 变量.findChild() 方法接受一个名称,并在调用它的树中搜索以找到具有该名称的节点.

Each node has a name variable. The findChild() method takes a name, and searches through the tree it was called on to find the node with that name.

为了进行递归搜索,我在子节点上调用 findChild() 而不是将子节点传递给 findChild() 方法.Print 语句显示该方法通过树向下传递,但是 result 变量在堆栈展开时设置为 null,因此该方法始终返回 null.我明白为什么要这样做,但我不明白如何展开这种类型的递归.任何帮助表示赞赏!

To do the recursive search, I call findChild() on the child node rather than passing the child node to the findChild() method. Print statements show me that the method gets down through the tree, but the result variable gets set to null as the stack is unwinded, so the method always returns null. I understand why it's doing this, but I don't understand how to unwind this type of recursion. Any help is appreciated!

我的findChild()方法:

public FileNode findChild(String name) {
    FileNode result = null;
        for (FileNode child : this.getChildren()) {
            if (child.getName() == name) {
                return child;
            } else {
                child.findChild(name);
            }
        }
    return result;
}

推荐答案

下面的小改动会有帮助吗?您的 else 条件永远不会赋值.

Will the following small change help? Your else condition is never assigning a value.

public FileNode findChild(String name) {
    FileNode result = null;
        for (FileNode child : this.getChildren()) {
            if (child.getName() == name) {
                result = child;
                break;
            } else {
                result = child.findChild(name);
                if (result != null)
                    break;
            }
        }
    return result;
}

这篇关于递归搜索树而不传递对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆