2016-09-07 46 views
1

我創建了一個二叉搜索樹,其中我一直在線上學習一個教程(https://www.youtube.com/watch?v=z0FDBGbf42Q:PaulProgramming)。我的代碼與本教程中的代碼幾乎相同,但是當我運行main時,出現了分段錯誤。我無法弄清楚爲什麼。如果有人能夠指出我的錯誤將會非常感激。是的,對於使用命名空間std抱歉,在我運行後我會適當地改變一切。BST中的段錯誤C++

BST.h

#ifndef BST_H 
#define BST_H 

class BST{ 
private: 
    struct node 
    { 
     int data; 
     node* left; 
     node* right; 
    }; 

    node* root; 

    void addLeafPrivate(int Data, node* ptr); 
    void printInOrderPrivate(node* ptr); 

public: 
    BST(); 
    node* createLeaf(int Data); 
    void addLeaf(int Data); 
    void printInOrder(); 

}; 
#endif 

BST.cpp

#include <iostream> 
#include <cstdlib> 
#include "BST.h" 

using namespace std; 

BST::BST(){ 
    root = NULL; 
} 



BST::node* BST::createLeaf(int Data){ 
    node* leaf = new node; 
    leaf->data = Data; 
    leaf->left = NULL; 
    leaf->right = NULL; 

    return leaf; 
} 

void BST::addLeafPrivate(int Data, node* ptr){ 
    if(root = NULL) 
     root = createLeaf(Data); 

    else if(Data < ptr->data){ 
     if(ptr->left != NULL) 
      addLeafPrivate(Data, ptr->left); 
     else 
      ptr->left= createLeaf(Data); 
    } 

    else if(Data > ptr->data){ 
     if(ptr->right != NULL) 
      addLeafPrivate(Data, ptr->right); 
     else 
      ptr->right= createLeaf(Data); 
    } 

    else 
     cout<< "The key " << Data << "already exist in the Binary Search Tree" << endl; 
} 

void BST::printInOrderPrivate(node* ptr){ 
    if(root != NULL){ 
     cout<< ptr->data << " " <<endl; 
     if(ptr->left != NULL) 
      printInOrderPrivate(ptr->left); 
     if(ptr->right != NULL) 
      printInOrderPrivate(ptr->right); 
    } 
    else 
     cout<<"Binary Search Tree is empty " << endl; 
} 

void BST::addLeaf(int Data){ 
    addLeafPrivate(Data, root); 
} 

void BST::printInOrder(){ 
    printInOrderPrivate(root); 
} 

主要

#include <iostream> 
#include <cstdlib> 
#include "BST.cpp" 

int main(){ 
    BST tree; 
    tree.addLeaf(2); 
    tree.addLeaf(5); 
    tree.addLeaf(10); 
    tree.addLeaf(0); 

    tree.printInOrder(); 

    return 0; 
} 
+1

你的'bst.h'和'main.cpp'文件是相同的。我認爲這是一個錯字,在這種情況下,您應該向我們展示* real *'bst.h'。 – paxdiablo

+1

你爲什麼在你的main.cpp中包含bst.cpp,是否是錯字? – HazemGomaa

+0

哎呀我的錯誤,讓我編輯 –

回答

3

在addLeafPrivate怎麼做,如果(根= NULL)而不是如果(根== NULL )

+1

我知道這會是這樣的!我只需要另一隻眼睛。非常感謝。什麼菜鳥的錯誤。 –

+0

我會在6分鐘內接受你的回答 –

+0

我已經接受你的回答,我爲浪費時間而道歉。但你非常幫助我。如果它不是用於stackoverflow社區的話,我一直在尋找更多小時的bug。 –