fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. struct Bst_Node{
  4. int val;
  5. Bst_Node*left,*right;
  6. };
  7. Bst_Node*Insert(Bst_Node*root,int x)
  8. {
  9. Bst_Node*newnode=new Bst_Node();
  10. newnode->val=x;
  11. newnode->left=NULL;
  12. newnode->right=NULL;
  13. Bst_Node*currnode;
  14. currnode=root;
  15. if(root==NULL)
  16. {
  17. root=newnode;
  18. return root;
  19. }
  20. while(1)
  21. {
  22. if(x<currnode->val)
  23. {
  24. if(currnode->left!=NULL)
  25. {
  26. currnode=currnode->left;
  27. }
  28. else
  29. {
  30. currnode->left=newnode;
  31. return root;
  32. }
  33. }
  34. else
  35. {
  36. if(currnode->right!=NULL)
  37. {
  38. currnode=currnode->right;
  39. }
  40. else
  41. {
  42. currnode->right=newnode;
  43. return root;
  44. }
  45. }
  46. }
  47. }
  48. void Preorder(Bst_Node*parent)
  49. {
  50. if(parent!=NULL)
  51. {
  52. cout<<parent->val<<" ";
  53. }
  54. if(parent->left!=NULL)
  55. {
  56. Preorder(parent->left);
  57. }
  58. if(parent->right!=NULL)
  59. {
  60. Preorder(parent->right);
  61. }
  62. }
  63. int main()
  64. {
  65. Bst_Node*root=NULL;
  66. root=Insert(root,4);
  67. root=Insert(root,5);
  68. root=Insert(root,1);
  69. Preorder(root);
  70. cout<<endl;
  71. }
  72.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
4 1 5