我创建了一个二叉搜索树,我一直在线学习教程(https://www.youtube.com/watch?v=z0FDBGbf42Q:PaulProgramming)。我的代码几乎与教程中的代码相同,但是当我运行main时,我遇到了分段错误。我无法弄清楚为什么。如果有人能够指出我的错误在哪里会非常感激。是的,抱歉使用命名空间std,我会在运行后正确地更改所有内容。
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;
}
答案 0 :(得分:3)
在addLeafPrivate中你做if(root = NULL)而不是if(root == NULL)