fork(1) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct node{
  5. int data;
  6. struct node *left;
  7. struct node *right;
  8. };
  9.  
  10. struct node* newNode(int num){
  11. struct node *nnode = (struct node*)malloc(sizeof(struct node));
  12. nnode->data=num;
  13. nnode->left=NULL;
  14. nnode->right=NULL;
  15. return nnode;
  16. }
  17.  
  18. //print tree
  19. void printTree(struct node *root){
  20. if(root==NULL) return;
  21. printf("%d\n",root->data);
  22. printTree(root->left);
  23. printTree(root->right);
  24. }
  25.  
  26. struct node* insert(struct node *root, int x){
  27. if(root==NULL){
  28. struct node *nnode=(struct node*)malloc(sizeof(struct node));
  29. nnode->data=x;
  30. nnode->left=NULL;
  31. nnode->right=NULL;
  32. root=nnode;
  33. return root;
  34. }
  35. else{
  36. if(x<root->data) insert(root->left,x);
  37. else insert(root->right,x);
  38. }
  39. }
  40.  
  41. int main()
  42. {
  43. struct node *root=NULL;
  44. root=insert(root, 5);
  45. struct node* mainroot=root;
  46. root=insert(root, 15);
  47. root=insert(root, 17);
  48. root=insert(root, 2);
  49. printTree(mainroot);
  50. return 0;
  51. }
  52.  
  53.  
Success #stdin #stdout 0s 2244KB
stdin
Standard input is empty
stdout
5