Skip to content

Instantly share code, notes, and snippets.

@joeke80215
Created February 17, 2019 13:29
Show Gist options
  • Save joeke80215/449fd3c94ffe954ff08b801d50007a5a to your computer and use it in GitHub Desktop.
Save joeke80215/449fd3c94ffe954ff08b801d50007a5a to your computer and use it in GitHub Desktop.
btree with C
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int Val;
struct Node *left;
struct Node *right;
};
struct Node* newNode()
{
struct Node* n;
n = (struct Node*)malloc(sizeof(struct Node));
n->right = 0x0;
n->left = 0x0;
return n;
}
struct Node* insert(struct Node* root,int val)
{
if (root == NULL) {
struct Node* n;
n = newNode();
n->Val = val;
return n;
}
if (val < root->Val) {
root->left = insert(root->left,val);
} else if (val > root->Val) {
root->right = insert(root->right,val);
}
return root;
}
void inoder(struct Node* root)
{
if (root) {
inoder(root->left);
printf("%d ",root->Val);
inoder(root->right);
}
}
struct Node* max_node(struct Node* root)
{
if (!root->right) {
return root;
}
return max_node(root->right);
}
struct Node* delete_node(struct Node* root,int val)
{
if (root == NULL) {
return NULL;
}
if (val < root->Val) {
root->left = delete_node(root->left,val);
}
else if (val > root->Val) {
root->right = delete_node(root->right,val);
}
else
{
if (root->left == NULL) {
root = root->right;
} else if (root->right == NULL)
{
root = root->left;
} else
{
struct Node* d;
d = max_node(root->left);
root->Val = d->Val;
root->left = delete_node(root->left,d->Val);
free(d);
}
}
return root;
}
/*
output:
2 5 10 13 15 16 40
2 5 10 13 15 16
2 10 13 15 16
max:16
*/
int main(void)
{
struct Node *root;
root = newNode();
root->Val = 10;
root = insert(root,5);
root = insert(root,15);
root = insert(root,16);
root = insert(root,13);
root = insert(root,2);
root = insert(root,40);
inoder(root);
printf("\n");
root = delete_node(root,40);
inoder(root);
printf("\n");
root = delete_node(root,5);
inoder(root);
printf("\n");
struct Node *maxNode;
maxNode = max_node(root);
printf("max:%d\n",maxNode->Val);
getchar();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment