Search:     Advanced search
Browse by category:
C/C++   |   Java   |   Oracle/Database   |   SAP   |   ASP .NET   |   Mainframe-DB2   |   Freshers

Write pseudocode to add a new node to a Binary Search Tree (BST)

Add comment
Views: 298
Votes: 0
Comments: 0

Here is a C code to construct a BST right from scratch...


#include

typedef struct node
{
int value;
struct node *right;
struct node *left;
}mynode;

mynode *root;

add_node(int value);
void postorder(mynode *root);
void inorder(mynode *root);
void preorder(mynode *root);

int main(int argc, char* argv[])
{
root = NULL;

add_node(5);
add_node(1);
add_node(-20);
add_node(100);
add_node(23);
add_node(67);
add_node(13);

printf("\nPreorder : ");
preorder(root);
printf("\n\nPostorder : ");
postorder(root);
printf("\n\nInorder : ");
inorder(root);

return(0);
}

// Function to add a new node...
add_node(int value)
{
mynode *prev, *cur, *temp;

temp = (mynode *) malloc(sizeof(mynode));
temp->value = value;
temp->right = NULL;
temp->left = NULL;

if(root==NULL)
{
printf("\nCreating the root..\n");
root = temp;
return;
}

prev=NULL;
cur=root;

while(cur!=NULL)
{
prev=cur;
cur=(valuevalue)?cur->left:cur->right;
}

if(value < prev->value)
prev->left=temp;
else
prev->right=temp;
}

 

void preorder(mynode *root)
{
if(root)
{
printf("[%d] ", root->value);
preorder(root->left);
preorder(root->right);
}
}


void postorder(mynode *root)
{
if(root)
{
postorder(root->left);
postorder(root->right);
printf("[%d] ", root->value);
}
}

 


void inorder(mynode *root)
{
if(root)
{
inorder(root->left);
printf("[%d] ", root->value);
inorder(root->right);
}
}

Others in this Category
document What purpose do the bitwise and, or, xor and the shift operators serve?
document Write a C program to count bits set in an integer?
document Construct a tree given its inorder and preorder traversal strings. Similarly construct a tree given its inorder and post For Inorder And Preorder traversals
document Check if the 20th bit of a 32 bit integer is on or off?
document Q: How would you retrieve rows from a DB2 table in embedded SQL?
document Q: What is the COBOL picture clause for a DB2 column defined as DECIMAL(11,2)?
document Q: What is the meaning of underscore ( ‘_’ ) in the LIKE statement?
document What is a threaded binary tree?
document What is an AVL tree?
document Q: What is DCLGEN ?
» More articles



RSS