My LeetCode grinding. Trying to do a problem a day.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct TreeNode {
  4. int val;
  5. struct TreeNode *left;
  6. struct TreeNode *right;
  7. };
  8. void insertIntoBSTRecursively(struct TreeNode*, int);
  9. struct TreeNode* insertIntoBST(struct TreeNode* root, int val) {
  10. insertIntoBSTRecursively(root, val);
  11. return root;
  12. }
  13. void insertIntoBSTRecursively(struct TreeNode* tree, int val) {
  14. if (val < tree->val) {
  15. // Go left if possible
  16. // else append a new TreeNode with this value
  17. if (tree->left != NULL) {
  18. insertIntoBSTRecursively(tree->left, val);
  19. } else {
  20. struct TreeNode *t = malloc(sizeof(struct TreeNode));
  21. t->val = val;
  22. t->left = NULL;
  23. t->right = NULL;
  24. tree->left = t;
  25. }
  26. } else {
  27. // Go right if possible
  28. // else append a new TreeNode with this value
  29. if (tree->right != NULL) {
  30. insertIntoBSTRecursively(tree->right, val);
  31. } else {
  32. struct TreeNode *t = malloc(sizeof(struct TreeNode));
  33. t->val = val;
  34. t->left = NULL;
  35. t->right = NULL;
  36. tree->right = t;
  37. }
  38. }
  39. }
  40. int main() {
  41. struct TreeNode *t2 = malloc(sizeof(struct TreeNode));
  42. t2->val = 2;
  43. t2->left = NULL;
  44. t2->right = NULL;
  45. struct TreeNode *t3 = malloc(sizeof(struct TreeNode));
  46. t3->val = 3;
  47. t3->left = NULL;
  48. t3->right = NULL;
  49. struct TreeNode *t = malloc(sizeof(struct TreeNode));
  50. t->val = 1;
  51. t->left = t2;
  52. t->right = t3;
  53. printf("Expecting to add value `4` to tree...\n");
  54. insertIntoBST(t, 4);
  55. // Here check t contains 4 now.
  56. if (t->right->right->val == 4) {
  57. printf("Value `4` added to Tree!\n");
  58. return 0;
  59. }
  60. return -1;
  61. }