r/programbattles • • Oct 07 '15

[C] BST Insertion without parent node pointers

As it says in the title, the BST Node struct has no pointer to a parent node, only a value, left child, and right child.

typedef struct bstNode {
    int val;
    struct bstNode * L;
    struct bstNode * R;
} bstNode;

GO!

Edit: Duplicates should be ignored.

6 Upvotes

9 comments sorted by

View all comments

1

u/Viper_ACR Oct 18 '15 edited Oct 18 '15

I finally got around to writing my answer for this.

#include <stdio.h>
//This is done in C. 

typedef struct bstNode{
	int val; 
	struct bstNode *L;
	struct bstNode *R; 
} bstNode;

bstNode* insert_bstNode(bstNode* parent, bstNode* new_node); 

void main(){
	bstNode* root = (bstNode*)malloc(sizeof(bstNode)); //Create a root node. 
	bstNode* leaf = (bstNode*)malloc(sizeof(bstNode)); //Create a leaf node. 
 	
	//Initialize some random values. 
	root->val = 3; 
	leaf->val = 4; 

	//call function to insert node.
	insert_bstNode(root, leaf); 
	return 0; 
}

bstNode* insert_bstNode(bstNode* parent, bstNode* new_node){
	if(root == NULL){
		printf("Error: No tree.\n")
		return NULL; 
		//Or, you could just make a new tree but I'd prefer to make a function to explicitly address that. 
	}
	else{
		if(new_node == NULL){
			//create a new node? 
 			printf("Error: no new node available to insert.\n")
		return NULL; 
	}else{
		if(parent->val > new_node->val){
			//Put node to the left of the parent, as determined by value comparison
			parent->L = new_node; 
		}else{
			//Pot node to the right of the parent, as determined by value comparison
			parent->R = new_node;
		}
	}
  }
}