2017-04-12 88 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); 
}