简体   繁体   English

递归搜索n叉树中的元素

[英]Search for an element in a n-ary tree recursively

I have a Tree class that has a nested private Node class.我有一棵树class,它有一个嵌套的私有节点class。
I wrote a method ( Search(T elem) ) that searches if the element given as parameter exists in the tree and sends a boolean.我编写了一个方法 ( Search(T elem) ),它搜索作为参数给出的元素是否存在于树中并发送 boolean。
However my problem is that this method only sends true if the element exists in the first branch of my tree and if not, it sends false.但是我的问题是,如果元素存在于我的树的第一个分支中,则此方法仅发送 true,如果不存在,则发送 false。 I must have mistaken somewhere in recursive calls.我一定在递归调用的某个地方弄错了。

for example, here in main i call search('C') and I get false although I should get true because C is in the second branch of my tree.例如,在 main 中,我调用search('C')并且我得到了错误,尽管我应该得到正确的结果,因为 C 在我的树的第二个分支中。
PS : Also I should mention that in this class, copy operator and constructor must be disabled and i can not use anything but raw pointer (no vector or smart pointers). PS:我还应该提到,在这个 class 中,必须禁用复制运算符和构造函数,除了原始指针(无向量或智能指针)之外我不能使用任何东西。
Thank you in advanced.提前谢谢你。

You shouldn't return children[i]->search(elem);你不应该返回children[i]->search(elem); directly.直接地。 So it will return false if elem is not found in the first branch, it will never get past the first child.因此,如果在第一个分支中找不到elem ,它将返回false ,它永远不会超过第一个孩子。 Only return there directly if it is found.只有找到时直接返回那里。 Otherwise try the other children.否则尝试其他孩子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM