fork download
  1. #include<iostream>
  2. #include<stack>
  3. using namespace std;
  4.  
  5. struct node{
  6.  
  7. int data;
  8. node *left;
  9. node *right;
  10.  
  11. };
  12.  
  13. node *getNewNode(int data){ //method for creating new node
  14.  
  15. node *newNode = new node();
  16. newNode->data=data;
  17. newNode->left=newNode->right = NULL;
  18. return newNode;
  19.  
  20. }
  21.  
  22. node *Insert(node *root , int data){ //Method for insert new data in tree
  23.  
  24. if(root == NULL){
  25. root = getNewNode(data);
  26. }
  27. else if(data>root->data){
  28. root->right = Insert(root->right,data);
  29. }
  30. else{
  31. root->left = Insert(root->left,data);
  32. }
  33.  
  34. return root;
  35.  
  36. }
  37.  
  38. void Print(node *root){ //Method for preorder traversal with recursion
  39.  
  40. if(root == NULL){
  41. return;
  42. }
  43.  
  44. cout<<root->data<<" ";
  45. Print(root->left);
  46.  
  47. Print(root->right);
  48.  
  49. }
  50.  
  51. void preOdr(node *root){ //Without recursion
  52.  
  53. stack<node*> stk;
  54. stk.push(root);
  55. while (!stk.empty()) {
  56. root=stk.top();
  57. stk.pop();
  58. cout<<root->data<<" "; // get and show top of stack
  59. if(root->right) // then push the childern
  60. stk.push(root->right);
  61. if(root->left)
  62. stk.push(root->left);
  63. }
  64. }
  65.  
  66. int main(){
  67.  
  68. node *root = NULL;
  69. root = Insert(root,10);
  70. root = Insert(root,6);
  71. root = Insert(root,15);
  72. root = Insert(root,3);
  73. root = Insert(root,9);
  74. root = Insert(root,11);
  75. root = Insert(root,17);
  76. root = Insert(root,11);
  77. root = Insert(root,62);
  78. root = Insert(root,135);
  79. root = Insert(root,30);
  80. root = Insert(root,98);
  81. root = Insert(root,117);
  82. root = Insert(root,176);
  83.  
  84. cout<<"Print"<<endl;
  85. Print(root);
  86. cout<<"Print-end"<<endl;
  87. cout<<endl;
  88. cout<<"Preo"<<endl;
  89. preOdr(root);
  90. cout<<"Preoend"<<endl;
  91.  
  92.  
  93. return 0;
  94. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
Print
10 6 3 9 15 11 11 17 62 30 135 98 117 176 Print-end

Preo
10 6 3 9 15 11 11 17 62 30 135 98 117 176 Preoend