Seu SlideShare está sendo baixado. ×

Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio

1 de 2 Anúncio

# Write a function that will insert a new key into a binary search tree-.docx

Write a function that will insert a new key into a binary search tree. Assume that the function takes two parameters: root and newValue , where root is the root of the binary search tree and newValue is the new key to be inserted into the binary tree.
in C++
Solution
#include<stdio.h>
#include<stdlib.h>

struct root
{
int value;
struct root *Left_Tree, *Right_Tree;
};
struct root *root_new(int item)
{
struct root *Temporary = (struct root *)malloc(sizeof(struct root));
Temporary->value = item;
Temporary->Left_Tree = Temporary->Right_Tree = NULL;
return Temporary;
}
void inorder_search(struct root *root)
{
if (root != NULL)
{
inorder_search(root->Left_Tree);
printf(\"%d \ \", root->value);
inorder_search(root->Right_Tree);
}
}
struct root* element_insert(struct root* root, int value)
{

if (root == NULL) return root_new(value);

if (value < root->value)
root->Left_Tree = element_insert(root->Left_Tree, value);
else if (value > root->value)
root->Right_Tree = element_insert(root->Right_Tree, value);

return root;
}

int main()
{

struct root *root = NULL;
// inserting the elements in to BST
root = element_insert(root, 50);
element_insert(root, 30);
element_insert(root, 20);
element_insert(root, 40);
element_insert(root, 70);
element_insert(root, 60);
element_insert(root, 80);

inorder_search(root); // to print the elements

return 0;
}
.

Write a function that will insert a new key into a binary search tree. Assume that the function takes two parameters: root and newValue , where root is the root of the binary search tree and newValue is the new key to be inserted into the binary tree.
in C++
Solution
#include<stdio.h>
#include<stdlib.h>

struct root
{
int value;
struct root *Left_Tree, *Right_Tree;
};
struct root *root_new(int item)
{
struct root *Temporary = (struct root *)malloc(sizeof(struct root));
Temporary->value = item;
Temporary->Left_Tree = Temporary->Right_Tree = NULL;
return Temporary;
}
void inorder_search(struct root *root)
{
if (root != NULL)
{
inorder_search(root->Left_Tree);
printf(\"%d \ \", root->value);
inorder_search(root->Right_Tree);
}
}
struct root* element_insert(struct root* root, int value)
{

if (root == NULL) return root_new(value);

if (value < root->value)
root->Left_Tree = element_insert(root->Left_Tree, value);
else if (value > root->value)
root->Right_Tree = element_insert(root->Right_Tree, value);

return root;
}

int main()
{

struct root *root = NULL;
// inserting the elements in to BST
root = element_insert(root, 50);
element_insert(root, 30);
element_insert(root, 20);
element_insert(root, 40);
element_insert(root, 70);
element_insert(root, 60);
element_insert(root, 80);

inorder_search(root); // to print the elements

return 0;
}
.

Anúncio
Anúncio