-
-
Save roongr2k7/c17acbf444e4b198ad2a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
struct _Node { | |
struct _Node *left; | |
int val; | |
struct _Node *right; | |
}; | |
typedef struct _Node Node; | |
Node * NewNode(int val) { | |
Node *node = malloc(sizeof(Node)); | |
node->left = NULL; | |
node->val = val; | |
node->right = NULL; | |
return node; | |
} | |
void AddValue(Node *node, int val) { | |
if (val <= node->val) { | |
if (node->left == NULL) { | |
node->left = NewNode(val); | |
} else { | |
AddValue(node->left, val); | |
} | |
return; | |
} | |
if (node->right == NULL){ | |
node->right = NewNode(val); | |
} else { | |
AddValue(node->right, val); | |
} | |
return; | |
} | |
void DeleteNode(Node *node) { | |
if (node->left != NULL) { | |
DeleteNode(node->left); | |
} | |
if (node->right != NULL) { | |
DeleteNode(node->right); | |
} | |
free(node); | |
} | |
int main() { | |
Node *root = NewNode(2); | |
AddValue(root, 20); | |
AddValue(root, 1); | |
AddValue(root, 0); | |
AddValue(root, 21); | |
printf("main root %d\n", root->val); | |
printf("left root %d\n", root->left->val); | |
printf("right root %d\n", root->right->val); | |
printf("left of left root %d\n", root->left->left->val); | |
printf("right of right root %d\n", root->right->right->val); | |
DeleteNode(root); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment