#include <stdio.h>
#include <stdlib.h>
struct
node {
int
key;
struct
node *left, *right;
};
struct
node* newnode(
int
element)
{
struct
node* temp = (
struct
node*)
malloc
(
sizeof
(
struct
node));
temp->key = element;
temp->left = temp->right = NULL;
return
temp;
}
struct
node* insert(
struct
node* root,
int
element)
{
if
(root == NULL)
return
newnode(element);
if
(element < root->key)
root->left = insert(root->left, element);
else
if
(element > root->key)
root->right = insert(root->right, element);
return
root;
}
void
inorder(
struct
node* mynode)
{
if
(mynode != NULL) {
inorder(mynode->left);
printf
(
"%d\t"
, mynode->key);
inorder(mynode->right);
}
}
struct
node* minValueNode(
struct
node* node)
{
struct
node* current = node;
while
(current->left != NULL)
current = current->left;
return
current;
}
struct
node* deleteNode(
struct
node* root,
int
key)
{
if
(root == NULL)
return
root;
if
(key < root->key)
root->left = deleteNode(root->left, key);
else
if
(key > root->key)
root->right = deleteNode(root->right, key);
else
{
if
(root->left == NULL) {
struct
node* temp = root->right;
free
(root);
return
temp;
}
else
if
(root->right == NULL) {
struct
node* temp = root->left;
free
(root);
return
temp;
}
struct
node* temp = minValueNode(root->right);
root->key = temp->key;
root->right = deleteNode(root->right, temp->key);
}
return
root;
}
checkpathCost(
int
pathweight,
int
thresoldPathWeight,
struct
node* currentNode,
struct
node* root)
{
pathweight = pathweight + currentNode->key;
if
((currentNode->left == NULL) && (currentNode->right == NULL)) {
if
(pathweight < thresoldPathWeight) {
pathweight = pathweight - currentNode->key;
printf
(
"need to Delete %d.\n"
, currentNode->key);
deleteNode(root, currentNode->key);
checkpathCost(0, thresoldPathWeight, root, root);
}
else
pathweight = pathweight - currentNode->key;
}
if
(currentNode->left != NULL) {
checkpathCost(pathweight, thresoldPathWeight,
currentNode->left, root);
}
if
(currentNode->right != NULL) {
checkpathCost(pathweight, thresoldPathWeight,
currentNode->right, root);
}
}
int
main()
{
int
thresoldPathWeight = 110;
struct
node* root = NULL;
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);
printf
(
"Inorder traversal of the given tree \n"
);
inorder(root);
printf
(
"\n"
);
checkpathCost(0, thresoldPathWeight, root, root);
printf
(
"Inorder traversal of the given tree \n"
);
inorder(root);
printf
(
"\n"
);
return
0;
}