在处理N-ary Trees遍历时,我完全陷入困境

时间:2011-10-29 23:05:21

标签: c++ algorithm

这就是问题。我想遍历我的N-ary树中的任意两个节点(在这种情况下是族树).Below是我从根到任意节点遍历的情况的简化代码:

#include <iostream>
#include <string>
using namespace std;

const int max=100;

//structure definition
//every children has only one parent
struct Tree {
   string name;
   int numChildren;
   Tree *children[max];
   ~Tree(){delete [] children;}
}; 

//Label the nodes that are supposed to be in the path
//Suppose the names of those nodes do not contain whitespaces,just trivial names
int *travel_point(Tree *tree,string s){
    Tree *node = new Tree;
    Tree *temp = new Tree;
    node = tree;

    int a[100],i=0,j;
    for(j=0;j<100;j++) a[j]=-1;
    while(tree){
        if(tree->name == s){
           a[i]=0;
           break;
        }
        else{
           for(j=0;j<node->numChildren;j++){
              if(travel_point(node->children[j],s)!=NULL){
                break;      
                }
              }
           a[i]=j+1;
           i++;
           temp=node->children[j];
           node=temp;
        }
    }
    if(a[i-1]==-1) return NULL;
    else a;
}

这大致是我一直在做的事情。因为每个孩子只有一个父母,所以从根到一个任意节点的路径也是唯一的。所以我想把所有其他路径设置为NULL,以防我可以采取在递归期间的优势。

我知道递归并不是一个好主意,但我只想尝试一下。

2 个答案:

答案 0 :(得分:1)

好的,我不想解决你的作业,但我想给你一些建议。 首先,树的递归函数通常是好的,通常树的高度不会太深,因此递归函数是好的。它们更易于编写和理解。

1)你不能在堆栈内存中返回一个指向数组的指针并假装它会起作用:)

2)你需要一个堆栈类,使用std::stack<int>,将一个非const引用传递给它作为参数,这样你就可以在所有函数中修改它,并返回一个布尔值,表明你是否找到了节点与否。然后,您可以将堆栈转换为向量或数组,但正如我想象的那样,您需要一个堆栈数据结构。

3)无需通过复制传递字符串,将const引用传递给它。 (const string&amp; s)

4)算法错误,重写它。多想想看。

5)析构函数错误,它不会杀死子节点但会执行无效的释放,需要循环。

6)我将使用std::vector<Tree*>

而不是[max]子树的数组

我认为这个功能就像......

bool travel_point(const Tree *tree, const string& s, stack<int>& result)

并使用它......

stack<int> path;
if (travel_point(mytree, "ciao", path))
{
    // print path
}

答案 1 :(得分:0)

这会崩溃并燃烧。您正在返回指向临时数组“a”的指针。也许你打算将“a”作为参数传递给函数。但是:应该返回的功能是什么?

顺便说一句:递归一个好主意。

相关问题