2017-04-12 45 views
1
void Btree<T>::InsertNode2(T data, BtreeNode* root) 
{ 
    if (root==NULL) 
    { 
     root = new BtreeNode (data); 
     return ; 
    } 
    if (data <= root->data) 
     InsertNode2(data, root->leftchild); 
    else 
     InsertNode2(data, root->rightchild); 
} 

为什么它不是正确的?根目录无法正确分配。在调用函数后,它仍然是NULL。如何通过递归在二叉树中插入元素?

+0

考虑,如果你是按值或引用传递根,根据您的语言。请参阅:http://stackoverflow.com/questions/32492184/binary-tree-root-is-null – DragonMoon

+0

谢谢。你是对的。 – user7857293

回答

0

它几乎正确。只是,由@DragonMoon说,所有你需要做的是按引用传递root

void Btree<T>::InsertNode2(T data, BtreeNode &* root) 
{ 
    if (root==NULL) 
    { 
     root = new BtreeNode (data); 
     return ; 
    } 
    if (data <= root->data) 
     InsertNode2(data, root->leftchild); 
    else 
     InsertNode2(data, root->rightchild); 
}