我正在尝试在C中编写树复制功能:

void tree_copy(treenode *source, treenode **dest)
{
    treenode *newtree;      //the new tree will be created using this as root
    treenode **bkup = &newtree;         //pointer to pointer, to keep backup of head of newtree

    /*
    Code to create new tree
    Traverses using *newtree
    And leaves *newtree pointing at last node created
    But *bkup still contains the address of the head node, right?
    */

    *dest = *bkup;  //assign the new tree created to the parameter
}

//I'm trying to invoke it like this:

int main(void)
{
    treenode *t1, *t2;

    create_tree(&t1);   //tested, already written function to create a tree. No bugs.
    tree_copy(t1, &t2);

    preorder(t2);       //tested, already written function for preorder traversal.
}


在执行此操作之后,应该包含新创建的树的根(t2)的节点仍然保持NULL。
为什么会这样呢?在备份新树的起始节点时,我的逻辑有什么问题?

任何帮助将不胜感激。

最佳答案

treenode *newtree;
treenode **bkup = &newtree;


bkup包含newtree变量的地址。 newtree变量将包含treenode的地址。

因此,bkup不包含存储在newtree中的指针的副本,它包含newtree变量的地址。存储那并没有真正的帮助,因为无论如何它都不会改变。不管您分配什么内容,newtree变量都将保留在同一位置。

如果要保存newtree初始值的副本,则必须在初始化后将其复制到newtree*变量:

treenode *root = newtree;
...
*dest = root;

09-06 21:32