2016-03-29 6 views
-3

次のメソッドを再帰的に書き込んで、ノードをバイナリツリーに挿入しようとしました。戦略は、基本的にNULLの左または右ポインタにノードを挿入することでした。主な機能要素をBinaryTreeに再帰的に挿入する

InsertElementInBinaryTree(&root , new BinaryTreeNode{8, NULL,NULL});

問題は、私はエラーが再帰であると考えているように、この呼び出しは常に、セグメンテーションフォールトエラーを返すことで、以下のように

typedef struct BinaryTreeNode { 
int data; 
BinaryTreeNode * left; 
BinaryTreeNode * right; 
} BinaryTreeNode; 

void InsertElementInBinaryTree(BinaryTreeNode *root, BinaryTreeNode *element) { 
    if(root) { 
     if(root -> left == NULL) root -> left = element; 
     else if(root -> right == NULL) root -> right = element; 
     InsertElementInBinaryTree(root -> left, element); 
     InsertElementInBinaryTree(root -> right, element); 
    } 
} 

メソッドが呼ばれているのですか?

+0

リンクリストやツリーなどの動的構造を使用する場合は、データを保存する前に** malloc()**を使用してヒープ上のストレージを予約する必要があります。アプリケーションを終了する前に** free()**する必要があります。そうしないと、アプリケーションを繰り返し使用するとすべてのヒープメモリが使用できなくなります。 –

答えて

0

あなたはいくつかの条件が欠けている:

 if (root->data > element->data) { 
     if (root->left == NULL) { 
      root->left = element; 
     } else { 
      InsertElementInBinaryTree(root->left, element); 
     } 
    } else { 
     if (root->right == NULL) { 
      root->right = element; 
     } else { 
     InsertElementInBinaryTree(root->right, element); 
      } 
    } 
0

を使用すると、任意の現在のノードのために、バイナリツリーを実装しようとしている場合は、左の部分木からのすべてのノードが現在のノードでdata、すべてのよりdata低くする必要があります右側のサブツリーからのdataが大きくなるはずです。

void InsertElementInBinaryTree(BinaryTreeNode *&root, BinaryTreeNode *element) { 
    if(root == NULL) { root = element; return;} 
    if(root -> data > element -> data) 
     InsertElementInBinaryTree(root->left, element); 
    else 
     InsertElementInBinaryTree(root->right, element); 
} 

そこで実際dataelement値がに挿入されます位置を定義します。また、rootポインタを変更するために、BinaryTreeNode *&rootを参照として渡しています。

使用法:

// declare root 
BinaryTreeNode* root; 
// insertion, no & operator before root 
InsertElementInBinaryTree(root, new BinaryTreeNode{8, NULL,NULL}); 
0

機能は次のよう

void InsertElementInBinaryTree(BinaryTreeNode * &root, int data) 
{ 
    if (root == nullptr) 
    { 
     root = new BinaryTreeNode { data, nullptr, nullptr }; 
    } 
    else if (data < root->data) 
    { 
     InsertElementInBinaryTree(root->left, data); 
    } 
    else 
    { 
     InsertElementInBinaryTree(root->right, data); 
    } 
} 

を見て、

InsertElementInBinaryTree(root , 8); 

とオブジェクトroot

01のように最初に定義する必要があるように呼ばれることができます
関連する問題