【发布时间】:2011-10-29 23:05:20
【问题描述】:
事情就是这样。我想遍历我的 N 叉树(在本例中为家谱)中的任意两个节点。下面是从根遍历到任意节点的情况的简化代码:
#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,以防万一递归期间的优势。
我知道递归不是一个好主意,但我只是想试一试。
【问题讨论】:
-
我不明白算法应该做什么,你能解释一下吗? travel_point 做什么以及 travel_point 返回什么?
-
你的成员
children不是new[]分配的数组,你不能delete[]它。 -
@chill 我试图设置一个析构函数,以便我可以递归地删除每个 Tree 类型结构的东西。那么正确的方法应该是什么?
-
@SalvatorePreviti travel_point 查找节点是否在我一直在寻找的路径上并返回 NULL 或指向存储标签的数组的指针。标签是子数组的索引。然后我将能够按索引遍历路径。
-
哪条路径?你的意思是要查找包含指定名称的节点的路径,将路径表示为整数序列?在这种情况下,这个函数是完全错误的:/