fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // ノード構造体の定義
  5. typedef struct node {
  6. int val;
  7. struct node *left;
  8. struct node *right;
  9. } Node;
  10.  
  11. // 新しいノードを作成する関数
  12. Node* createNode(int val) {
  13. Node* newNode = (Node*)malloc(sizeof(Node));
  14. newNode->val = val;
  15. newNode->left = newNode->right = NULL;
  16. return newNode;
  17. }
  18.  
  19. // ソート済み配列からバランスの良いBSTを再帰的に構築する関数
  20. Node* buildBalancedBST(int arr[], int start, int end) {
  21. if (start > end) return NULL;
  22. int mid = (start + end) / 2;
  23. Node* root = createNode(arr[mid]);
  24. root->left = buildBalancedBST(arr, start, mid - 1);
  25. root->right = buildBalancedBST(arr, mid + 1, end);
  26. return root;
  27. }
  28.  
  29. // 中間順(In-Order)走査で確認
  30. void inorderTraversal(Node* root) {
  31. if (!root) return;
  32. inorderTraversal(root->left);
  33. printf("%d ", root->val);
  34. inorderTraversal(root->right);
  35. }
  36.  
  37. // メモリ解放
  38. void freeTree(Node* root) {
  39. if (!root) return;
  40. freeTree(root->left);
  41. freeTree(root->right);
  42. free(root);
  43. }
  44.  
  45. // メイン関数
  46. int main() {
  47. int arr[] = {2, 3, 5, 8, 13, 21}; // ソート済みの配列
  48. int n = sizeof(arr) / sizeof(arr[0]);
  49.  
  50. Node* root = buildBalancedBST(arr, 0, n - 1);
  51.  
  52. printf("In-Order Traversal: ");
  53. inorderTraversal(root); // 昇順で表示されるはず
  54. printf("\n");
  55.  
  56. freeTree(root); // メモリを解放
  57.  
  58. return 0;
  59. }
  60.  
  61.  
Success #stdin #stdout 0s 5308KB
stdin
arr
stdout
In-Order Traversal: 2 3 5 8 13 21