fork download
  1.  
  2.  
  3.  
  4. #include <stddef.h> // NULL
  5. #include <stdlib.h>
  6. #include <stdio.h>
  7. #define MaxSize 10
  8. typedef struct node {
  9. int data;
  10. struct node* lchild, * rchild;
  11. } TreeNode;
  12. TreeNode *create(int nums[], int n);
  13. void preorder(TreeNode *root);
  14.  
  15.  
  16. TreeNode* newNode(int v) {
  17. TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
  18. node->data = v;
  19. node->lchild = node->rchild = NULL;
  20. return node;
  21. }
  22. void insert(TreeNode** root, int x)
  23. {
  24. if (*root == NULL) {
  25. *root = newNode(x);
  26. return;
  27. }
  28. if ((*root)->data < x) {
  29. insert(&(*root)->lchild, x);
  30. }
  31. else {
  32. insert(&(*root)->rchild, x);
  33. }
  34. }
  35. TreeNode *create(int nums[], int n)
  36. {
  37. TreeNode* root = NULL;
  38. for (int i = 0; i < n; i++) {
  39. insert(&root, nums[i]);
  40. }
  41. return root;
  42. }
  43. void preorder(TreeNode* root)
  44. {
  45. if (root == NULL) {
  46. return;
  47. }
  48. printf("%d ", root->data);
  49. preorder(root->lchild);
  50. preorder(root->rchild);
  51. }
  52.  
  53. int main(int argc, char* argv[])
  54. {
  55. int nums[MaxSize] = { 7, 4, 3, 8, 10, 12, 17, 0, -1, 3 };
  56.  
  57. TreeNode* root = create(nums, MaxSize);
  58. preorder(root);
  59. return 0;
  60. }
  61.  
  62.  
Success #stdin #stdout 0.01s 5528KB
stdin
Standard input is empty
stdout
7 8 10 12 17 4 3 0 3 -1