当前位置: 代码迷 >> C语言 >> 复制一棵树解决方案
  详细解决方案

复制一棵树解决方案

热度:9812   发布时间:2013-02-26 00:00:00.0
复制一棵树
本帖最后由 yass8899 于 2013-01-24 12:51:22 编辑
复制一棵树的一部分,从开始复制的节点开始,打算用递归复制每个节点,可是不知道新节点如何指向孩子节点

struct node
{
...
int num_number; //孩子节点数
node **children; //指向children节点的指针
}
void copy_tree(node *node, node *T)
{
int i;
char number[12] = {0}; //if中使用
int n = node->num_children; 
if (node == NULL)
T = NULL;
if(...)
{
.... //作节点的复制
}
else
{
                ....  //作节点的复制
}
for(i=0; i<n; i++)
copy_tree(node->children[i], T->children[i]); //想用递归对孩子节点复制,但新节点是没有孩子节点,怎么办? 即不存在T->children. 怎样复制孩子,再把孩子节点接上去?
}

请高手指点,谢谢!

------解决方案--------------------------------------------------------

//楼主你写的代码逻辑有些错误。我修正了一下。
struct node
{
...
int num_number; //孩子节点数
node **children; //指向children节点的指针
}
void copy_tree(node *node, node *T)
{
    int i;
    char number[12] = {0}; //if中使用
    int n = node->num_children; 
    if (node == NULL){
        T = NULL;
    }
    else{//1. add else here
//2. TODL: copy value of node to T here
//please add here on your own
     if(...){//3. n==0
  //4. T->children = NULL;
     }
     else//n>0
     {
         //5. create n node*
T->children = (node **)malloc(sizeof(node *));
//recursion
     for(i=0; i<n; i++){
         copy_tree(node->children[i], T->children[i]);
}
//想用递归对孩子节点复制,但新节点是没有孩子节点,怎么办?
//即不存在T->children. 怎样复制孩子,再把孩子节点接上去?
     }
    }
}
  相关解决方案