123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- #include <stdio.h>
- #include <stdlib.h>
-
- struct TreeNode {
- int val;
- struct TreeNode *left;
- struct TreeNode *right;
- };
-
- void insertIntoBSTRecursively(struct TreeNode*, int);
-
- struct TreeNode* insertIntoBST(struct TreeNode* root, int val) {
- insertIntoBSTRecursively(root, val);
- return root;
- }
-
- void insertIntoBSTRecursively(struct TreeNode* tree, int val) {
- if (val < tree->val) {
- // Go left if possible
- // else append a new TreeNode with this value
- if (tree->left != NULL) {
- insertIntoBSTRecursively(tree->left, val);
- } else {
- struct TreeNode *t = malloc(sizeof(struct TreeNode));
- t->val = val;
- t->left = NULL;
- t->right = NULL;
- tree->left = t;
- }
- } else {
- // Go right if possible
- // else append a new TreeNode with this value
- if (tree->right != NULL) {
- insertIntoBSTRecursively(tree->right, val);
- } else {
- struct TreeNode *t = malloc(sizeof(struct TreeNode));
- t->val = val;
- t->left = NULL;
- t->right = NULL;
- tree->right = t;
- }
- }
- }
-
- int main() {
- struct TreeNode *t2 = malloc(sizeof(struct TreeNode));
- t2->val = 2;
- t2->left = NULL;
- t2->right = NULL;
- struct TreeNode *t3 = malloc(sizeof(struct TreeNode));
- t3->val = 3;
- t3->left = NULL;
- t3->right = NULL;
- struct TreeNode *t = malloc(sizeof(struct TreeNode));
- t->val = 1;
- t->left = t2;
- t->right = t3;
- printf("Expecting to add value `4` to tree...\n");
- insertIntoBST(t, 4);
- // Here check t contains 4 now.
- if (t->right->right->val == 4) {
- printf("Value `4` added to Tree!\n");
- return 0;
- }
- return -1;
- }
|