fork download
  1. #include <iostream>
  2. using namespace std;
  3. struct node{ int data;
  4. struct node* left;
  5. struct node*right;
  6. };
  7. struct node* createnode(int num)
  8. {
  9. struct node* p=(struct node*)malloc(sizeof(struct node));
  10. p->data=num;
  11. p->left=NULL;
  12. p->right=NULL;
  13. return p;
  14. }
  15. struct node* findlca(struct node*root,int n1,int n2)
  16. {
  17. if(root==NULL || root->data==n1 || root->data==n2)
  18. return root;
  19. struct node* leftlca=findlca(root->left,n1,n2);
  20. struct node* rightlca=findlca(root->right,n1,n2);
  21. if(leftlca && rightlca)
  22. return root;
  23. if(leftlca!=NULL)
  24. return (leftlca);
  25. else
  26. return(rightlca);
  27. }
  28. void preordertraversal(struct node* root)
  29. {
  30. if(root==NULL)
  31. return;
  32. printf("%d" ,root->data);
  33. preordertraversal(root->left);
  34. preordertraversal(root->right);
  35. }
  36. void inordertraversal(struct node* root)
  37. {
  38. if(root==NULL)
  39. return;
  40. inordertraversal(root->left);
  41. printf("%d" ,root->data);
  42. inordertraversal(root->right);
  43. }
  44. void postordertraversal(struct node* root)
  45. {
  46. if(root==NULL)
  47. return;
  48. postordertraversal(root->left);
  49. postordertraversal(root->right);
  50. printf("%d" ,root->data);
  51. }
  52.  
  53. int main() {
  54. struct node* root=createnode(5);
  55. root->left=createnode(2);
  56. root->left->left=createnode(1);
  57. root->left->right=createnode(3);
  58. root->right=createnode(7);
  59. root->right->left=createnode(6);
  60. root->right->right=createnode(8);
  61. struct node* tree =findlca(root,1,8);
  62. printf("%d ",tree->data);
  63. printf("\n");
  64. preordertraversal(root);
  65. printf("\n");
  66. inordertraversal(root);
  67. printf("\n");
  68. postordertraversal(root);
  69. return 0;
  70. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
5 
5213768
1235678
1326875