2016-05-18 77 views
0

我想知道这个错误为什么它被占领了!来自C++的BST代码

class node 
{ 
public: 
    int data ; 
    node *left ; 
    node *right ; 
} ; 

class tree 
{ 
public: 
    node * root ; 

public: 
    tree() 
    { 
     root = NULL ; 
    } 
    node* Insert(node* root, int num) // 
    { 
     if(root == NULL) // root is null 
     { 
      node * temp = new node() ; 
      temp->left = NULL ; 
      temp->right = NULL ; 
      temp->data = num ; 
      root = temp ; 
     } 
     else if (num < root->data) 
     { 
      root->left = Insert(root->left, num) ; 
     } 
     else if (num > root->data) 
     { 
      root->right = Insert(root->right, num) ; 
     } 
     return root ; 
    } 
} ; 
void main() 
{ 
    tree * Tree = new tree() ; 
    Tree->Insert(Tree->root, 10) ; 
    cout << temp->root->data ; 
} 

当我执行这个代码,比我预期的根的数据是10 但实际上,根是空的。 为什么root null?

我不知道!!!!

请教我!!!

回答

1

root永远不会在您的Insert方法中更新。传递给方法root与成员变量不同。

不喜欢以下内容:

或通过根的地址,或使用this->root =无处不在方法内部。

整体设计需要重新审查,我想你想娱乐和学习

另外,还要确保你释放内存一旦你完成。目前你在任何地方都有内存泄漏。