2011-09-24 74 views
0

需要幫助瞭解爲什麼下面的基本二叉搜索樹插入代碼不起作用。由於我一直在使用C#,恐怕我忘了一些C++。此外,任何改善編碼風格的建議都會非常有幫助。 (我知道我不釋放內存截至目前)二進制搜索樹插入

struct Node 
    { 
     int data; 
     Node* lChild; 
     Node* rChild; 

     Node(int dataNew) 
     { 
      data = dataNew; 
      lChild = NULL; 
      rChild = NULL; 
     } 
    }; 

    class BST 
    { 
    private: 
     Node* root; 

     void Insert(int newData, Node* &cRoot) //is this correct? 
     { 
      if(cRoot == NULL) 
      { 
       cRoot = new Node(newData); 
       return; 
      } 

      if(newData < cRoot->data) 
       Insert(cRoot->data, cRoot->lChild); 
      else 
       Insert(cRoot->data, cRoot->rChild); 
     } 

     void PrintInorder(Node* cRoot) 
     { 
      if(cRoot != NULL) 
      { 
       PrintInorder(cRoot->lChild); 
       cout<< cRoot->data <<" ";; 
       PrintInorder(cRoot->rChild); 
      } 
     } 

    public: 
     BST() 
     { 
      root = NULL; 
     } 

     void AddItem(int newData) 
     { 
      Insert(newData, root); 
     } 

     void PrintTree() 
     { 
      PrintInorder(root); 
     } 
    }; 

    int main() 
    { 
     BST *myBST = new BST(); 
     myBST->AddItem(5); 
     myBST->AddItem(7); 
     myBST->AddItem(1); 
     myBST->AddItem(10); 
     myBST->PrintTree(); 
    } 

回答

2

這在我看來,

Insert(cRoot->data, cRoot->lChild); 

應改爲

Insert(newData, cRoot->lChild); 
+0

啊!謝謝,現在它工作。 – Nemo