fork(1) download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct node{
  5. int data;
  6. struct node* left;
  7. struct node* right;
  8. };
  9.  
  10. typedef struct node* Node;
  11.  
  12.  
  13. Node insert(Node root, int num){
  14. if(root==NULL){
  15. Node newNode=(Node)malloc(sizeof(Node));
  16. newNode->data=num;
  17. newNode->left=NULL;
  18. newNode->right=NULL;
  19. return newNode;
  20. }
  21.  
  22. if(root->data>num)
  23. root->left=insert(root->left,num);
  24. else
  25. root->right=insert(root->right,num);
  26. return root;
  27. }
  28.  
  29. void printinorder(Node root){
  30. if(root==NULL)
  31. return;
  32.  
  33. printinorder(root->left);
  34. cout<<root->data<<endl;
  35. printinorder(root->right);
  36. }
  37.  
  38.  
  39.  
  40.  
  41.  
  42. int main(){
  43.  
  44. Node tree=NULL;
  45. tree=insert(tree,1);
  46. tree=insert(tree,2);
  47. tree=insert(tree,3);
  48. tree=insert(tree,4);
  49. tree=insert(tree,5);
  50. tree=insert(tree,6);
  51. tree=insert(tree,7);
  52. printinorder(tree);
  53.  
  54.  
  55. }
  56.  
Success #stdin #stdout 0s 15232KB
stdin
Standard input is empty
stdout
1
2
3
4
5
6
7