このコードがどこで失敗しているのか分かりません。これはクラスの割り当てのためのもので、最低の高さでその場所にバイナリツリーに挿入する必要があります。C++バイナリツリー挿入/高さ
高さ関数に明らかなセグメント化エラーが発生しています。
class Node {
public:
Node();
Node(int);
private:
friend class bT;
int data;
Node* left;
Node* right;
};
class bT {
public:
bT();
virtual void insert(int);
int height() const;
unsigned size() const;
protected:
Node* root;
private:
void insert(Node*&, int);
int height(Node*) const;
};
そして、私のメインのファイル:
int bT::height() const {
//Returns -1 when root does not exist
if (root == NULL)
return -1;
//Calls private recursive method. Uses taller height
int lheight = height(root->left);
int rheight = height(root->right);
if (lheight > rheight)
return lheight;
else
return rheight;
}
void bT::insert(int x) {
//Inserts new node at root if root does not exist
if (root == NULL){
Node node(x);
root = &node;
}
//Calls private recursive method to insert.
else {
int lheight = height(root->left);
int rheight = height(root->right);
if (lheight <= rheight)
insert(root->left, x);
else
insert(root->right, x);
}
}
int bT::height(Node* r) const {
//Base Case: Returns 0 when node does not exist
if (r == NULL)
return 0;
//Calls private recursive method. Uses taller height
int lheight = height(r->left);
int rheight = height(r->right);
if (lheight > rheight)
return 1 + lheight;
else
return 1 + rheight;
}
void bT::insert(Node*& r, int x){
//Base Case: Sets r = new node when node does not exist
if (r == NULL) {
Node node(x);
r = &node;
}
//Recursive Call: Calls insert function for node with lower height
else {
int lheight = height(r->left);
int rheight = height(r->right);
if (lheight <= rheight)
insert(r->left, x);
else
insert(r->right, x);
}
}
あなたの 'ルート'は[ダングリングポインタ](http://stackoverflow.com/q/17997228/5980430)です。あなたの挿入メソッドのコードが間違っています。 –
@appleappleありがとうございますが、私はそのページを読んでいますが、私はまだ混乱しています。クラスヘッダーを変更せずにこの問題を解決するにはどうすればよいですか(それは私たちに与えられ、明示的に変更しないように指示しています)。 – Tommy
@ 5980430私のデフォルトのコンストラクタでNodeのために、私はNULLへの左と右のポインタを初期化します。 – Tommy