fork download
  1. #include<iostream>
  2. #include<stdlib.h>
  3. using namespace std;
  4.  
  5. typedef struct tree{
  6. int val;
  7. struct tree *left;
  8. struct tree *right;
  9. }tree;
  10.  
  11. tree* insert(tree* root, int val)
  12. {
  13. if(root == NULL)
  14. {
  15. tree* temp = (tree*) malloc(sizeof(tree));
  16. temp->val = val;
  17. temp->left = NULL;
  18. temp->right = NULL;
  19. return temp;
  20. }
  21.  
  22. tree* node = (tree*) malloc(sizeof(tree));
  23. if(root->val < val)
  24. root->right = insert(root->right, val);
  25. else
  26. root->left = insert(root->left, val);
  27. return root;
  28. }
  29.  
  30. tree* buildBST(int preOrder[], int length)
  31. {
  32. tree* root;
  33. if(length != 0)
  34. {
  35. root = (tree*) malloc(sizeof(tree));
  36. root->val = preOrder[0];
  37. root->left = NULL;
  38. root->right = NULL;
  39. }
  40. else
  41. return NULL;
  42.  
  43. for(int i = 1; i < length; i++)
  44. {
  45. root = insert(root, preOrder[i]);
  46. }
  47.  
  48. return root;
  49. }
  50.  
  51. void printInOrder(tree* BST)
  52. {
  53. if(BST == NULL) return;
  54. printInOrder(BST->left);
  55. cout << BST->val << " ";
  56. printInOrder(BST->right);
  57. }
  58.  
  59. void printPreOrder(tree* BST)
  60. {
  61. if(BST == NULL) return;
  62. cout << BST->val << " ";
  63. printPreOrder(BST->left);
  64. printPreOrder(BST->right);
  65. }
  66.  
  67. int main(void)
  68. {
  69. int preOrder[] = {10, 5, 3, 4, 6, 11, 13, 12};
  70. tree* BST = buildBST(preOrder, sizeof(preOrder) / sizeof(int));
  71. printInOrder(BST);
  72. cout << endl;
  73. printPreOrder(BST);
  74. cout << endl;
  75. }
Success #stdin #stdout 0.01s 2812KB
stdin
Standard input is empty
stdout
3 4 5 6 10 11 12 13 
10 5 3 4 6 11 13 12