2011-04-17 55 views
1

我正在为二叉搜索树编写构造函数,问题是树中的帮助函数被无限调用,最终会产生堆栈溢出。二进制搜索树的复制构造函数被无限调用

void copyTree(myTreeNode* & copy, const myTreeNode* & originalTree) 
{ 
    if(originalTree==NULL) 
    { 
     copy=NULL; 
    } 
    else 
    { 
     copy=new myTreeNode(); 
     cout<<"This is the data my friend: "<<endl<<copy->data.getCharacter()<<endl; 
     copy->data=originalTree->data; 
     copyTree(copy->left, originalTree->getLeft()); 
     copyTree(copy->right,originalTree->getRight()); 
    } 
} 

//this is the copy constructor for the tree 
myTree (const myTree & copy) 
{ 
    this->copyTree(this->root,copy.getRoot()); 
} 

//and this is the way I have written the getLeft and getRight Functions 
//they both return references to the left and rightNodes 

const myTreeNode *& getLeft() const 
{ 
    const myTreeNode* ptr=NULL; 
    if(this->left) 
    { 
     ptr=this->left; 
    } 
    return ptr; 
} 

P.S数据对象不是原始数据类型,但它没有动态内存分配。

+1

是'myTreeNode :: left'总是被初始化为'NULL'?如果不是,你可能永远不会达到基本情况,因为getLeft()永远不会返回NULL。不过,我认为垃圾价值会导致分段错误。 – 2011-04-17 21:28:21

回答

4

我不知道这可能是如何造成无限递归,但你的getLeft()功能似乎是可疑的。您正在返回对堆栈中某个东西的引用。谁知道那之后发生了什么。它看起来像你一直在内存中反复使用同一个插槽,所以你可能会创建一个循环而不是树。

更改它,使其返回一个指针,而不是对指针的引用(删除'&')。

+0

好的调用 - 我认为你对内存行为的感觉与我期望任何C编译器在正常情况下所做的一致。 – leoger 2011-04-18 00:10:59

+0

你是对的这是通过引用的返回,使我在 – sola 2011-04-18 23:57:21

1

@JCooper想通了 - 我只是提供示例代码。 getLeft()函数应该看起来更像这样。请注意,我没有创建任何NEW变量,所以没有堆栈寿命问题。

const myTreeNode * getLeft() const 
{ 
    //may be NULL 
    return this->left; 
} 

(编辑:做代码更简洁感谢@molbdnilo!)

+1

你可以更简洁地表达:如果'this-> left'非空,则返回'this-> left';如果它为null,则返回空指针,它是'this-> left'的值。所以你可以用'return this-> left'替换'getLeft'的整个主体。 – molbdnilo 2011-04-18 04:43:09

+0

谢谢,修正了这个问题 – sola 2011-04-18 23:56:22

+0

我的意图最初是为了明确两个案例的目的应该是冗长的。现在,我认为你说得对,这太浪费了,评论可能是更清晰的选择! – leoger 2011-04-19 05:23:05