用于树数据结构的递归函数

Recursive function to for tree data structure

本文关键字:递归函数 数据结构 用于      更新时间:2023-10-16

图像在这里顶部值是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;