用于树数据结构的递归函数
Recursive function to for tree data structure
图像在这里顶部值是ID,底部与您无关。我需要写一个函数,它接收树顶元素(它们被称为部委),然后走到树下,检查树上的一些子元素是否附着在他自己身上(或其他大部委)。基本上,正确或错误的回报将是理想的。我只是无法生成函数,因为它在最后一次返回时总是返回false,因为第一个被选中的孩子没有指向牧师。最后,它确实返回了true,但这有什么用呢。
继续使用代码:Element(与链表中的节点非常相似),但单个node有一个所有子指针的数组。
class Element {
public:
int id;
int value;
bool is_parent;
bool is_ministry;
bool is_children;
int children_count;
int children_in;
bool is_visited;
Element **children; //CHILDREN ARRAY
Element* next; //TO NOT LOSE ELEMENTS
Element(int _id,int _value,int _children_count=0,bool _is_ministry=false){
this->id=_id;
this->value=_value;
this->is_ministry=_is_ministry;
this->children_in=0;
this->children_count=_children_count;
this->next=NULL;
this->is_visited=false;
this->is_children=false;
if(_children_count>0){
this->is_parent=true;
this->children = new Element*[_children_count];
}
else{
this->is_parent=false;
this->children=NULL;
}
}
~Element(){
///delete children;
}
};
主要递归函数:
bool error_1_recursive(Element *_parent){
cout << "Inspecting: (in this example the first to come here is id11) " << _parent->id<< " ";
if(_parent->is_ministry ) {
cout << "Found ministry";
return true;
}
///Did not find ministry, going further down the recursion.
if(_parent->is_parent){
for(int i=0;i<_parent->children_in;i++){
error_1_recursive(_parent->children[i]);
}
}
}
我不能为它做1个函数,因为我需要检查给定的对象是否是部委,因为我首先需要通过的对象实际上是部委。
void error_1_recursive_container(Element *_parent){
cout << "Receives main child with id " << _parent->id << " ";
Here it goes trough main child children and recursion can start.
for(int i=0;i<_parent->children_in;i++){
if(error_1_recursive(_parent->children[i])==true){
cout << "The main child has atleast 1 child that points to ministry" << endl;
}
}
}
最后,还有一条穿过树的路。
void Going_around(Element *_parent){
cout << _parent->id << " ";
if(_parent->is_parent){
for(int i=0;i<_parent->children_in;i++){
Going_around(_parent->children[i]);
}
}
}
您需要在error_1_recursive
的末尾添加一个return语句。在循环中调用时,需要使用error_1_recursive
的结果。如果你想返回true,只要你得到任何真实的结果:if (
递归调用) return true;
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何在Elixir中调用递归函数并行
- 递归函数有效,但无法记忆
- 为什么我的递归函数按降序打印,然后按升序打印?
- 为什么递归函数的最终输出是 5?
- 有没有办法使用递归函数找到数组中最小值的 INDEX?C++
- 如何将记忆应用于此递归函数?
- 如何从递归函数中完全返回,该函数给出了每个函数结果的累积相加?
- 无穷大而循环时具有递归函数
- 即使没有调用这个递归函数,它是如何工作的?
- 如何使此递归函数从给定的起始位置返回最小的整数?
- 查找存储在二叉搜索树的所有非叶子中的数据总和?(返回整数的独立递归函数
- 我如何实现递归函数的模板,该模板允许C 中的许多不确定数据类型的参数
- 如果结构作为递归函数中的参数传递,如何初始化结构的成员变量
- 在其静态递归函数中展开结构类型模板参数包
- 如何编写递归函数来计算图形数据结构中的最短路径
- 如何递归调用具有结构数组作为参数的函数
- 用于树数据结构的递归函数
- C++向量在递归函数中丢失数据
- 通过结构调用递归函数