简体   繁体   中英

Insert element into BinaryTree recursively

I have attempted to write the following method recursively to insert a node into a binary tree. The strategy was to basically insert the node in any NULL left or right pointers.

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);
    }
}

The method is called as follows in the main function

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

The issue is that this call always returns a segmentation fault error so I believe the error is in the recursion ?

You're missing some conditions:

     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);
          }
     }

If you are trying to implement binary tree then for any current node all the nodes from the left subtree should have lower data than the data in current node and all the data from the right subtree should be greater.

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);
}

So actually data values define the position element will inserted at. Also I'm passing BinaryTreeNode *&root as a reference in order the root pointer to be modifiable.

Usage:

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

The function can look the following way

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 );
    }
}

and called like

InsertElementInBinaryTree( root , 8 );

and the object root should be defined initially like

BinaryTreeNode *root = nullptr;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM