【问题标题】:Recursive function to for tree data structure树数据结构的递归函数
【发布时间】:2016-03-18 05:52:25
【问题描述】:

Image is here 顶值是ID,底值与你无关。我需要编写一个函数来接收树顶元素(它们被称为部委)并沿着树向下检查它的一些孩子是否与他本身(或其他大部委)相关联。基本上正确或错误的回报将是理想的。我只是无法创建该函数,因为它总是在最后一次返回时返回 false,因为第一个检查的子项没有指向该部。最后它确实返回true,但那有什么用。

接着代码: 元素(很像链表中的节点)但单个节点有一个包含所有子指针的数组。

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]);
            }
        }
    }

【问题讨论】:

    标签: c++ recursion data-structures tree


    【解决方案1】:

    您需要在error_1_recursive 的末尾添加一个return 语句。 在循环中调用时,您需要使用error_1_recursive 的结果。 如果你想返回真,只要你得到任何真结果: if (递归调用) return true;

    【讨论】:

      猜你喜欢
      • 2018-08-27
      • 2019-04-14
      • 2015-04-26
      • 2015-01-05
      • 1970-01-01
      • 2021-08-03
      • 2011-11-25
      • 2018-11-19
      • 1970-01-01
      相关资源
      最近更新 更多