Advertisement
AyAks69

Untitled

Oct 14th, 2022
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. /******************************************************************************
  2.  
  3. Online C++ Compiler.
  4. Code, Compile, Run and Debug C++ program online.
  5. Write your code in this editor and press "Run" button to compile and execute it.
  6.  
  7. *******************************************************************************/
  8. #include<bits/stdc++.h>
  9. using namespace std;
  10.  
  11. struct Node{
  12. int data;
  13. struct Node* left;
  14. struct Node* right;
  15.  
  16. };
  17.  
  18. struct Node* newNode(int val){
  19. struct Node* temp = new Node;
  20. temp->data = val;
  21. temp->left = NULL;
  22. temp->right = NULL;
  23. }
  24.  
  25. Node* insert(Node* node , int val){
  26. if(node == NULL){
  27. return newNode(val);
  28. }
  29. if(val<node->data){
  30. node->left = insert(node->left , val);
  31. }
  32. else if(val>node->data){
  33. node->right = insert(node->right , val);
  34. }
  35. return node;
  36. }
  37.  
  38.  
  39. void ExternalNodes(Node* root ){
  40.  
  41. if(root==NULL){
  42. return;
  43. }
  44. if(root->left==NULL&& root->right == NULL){
  45. cout<<root->data<<" ";
  46. }
  47.  
  48. ExternalNodes(root->left );
  49. ExternalNodes(root->right );
  50.  
  51. }
  52.  
  53.  
  54. void InternalNodes(Node* root ){
  55.  
  56. if(root==NULL){
  57. return;
  58. }
  59. if(root->left!=NULL || root->right != NULL){
  60. cout<<root->data<<" ";
  61. }
  62.  
  63. InternalNodes(root->left );
  64. InternalNodes(root->right );
  65.  
  66. }
  67.  
  68. int height(Node* root){
  69. if(root==NULL){
  70. return 0;
  71. }
  72. return 1+ max(height(root->left),height(root->right));
  73. }
  74.  
  75. void Tree(int a[] , int n){
  76. struct Node* root = NULL;
  77. root = insert(root,a[0]);
  78. for(int i=1 ; i<n;i++){
  79. root = insert(root,a[i]);
  80. }
  81. int b[n] ;
  82. cout<<"External Nodes"<<endl;
  83. ExternalNodes(root);
  84.  
  85. cout<<"\nInterrnal Nodes"<<endl;
  86. InternalNodes(root );
  87.  
  88. cout<<"\nHeight of Tree"<<endl;
  89. cout<<height(root);
  90.  
  91.  
  92. }
  93.  
  94.  
  95. int main(){
  96. int n;
  97. cout<<"Enter the number of elements: ";
  98. cin>>n;
  99. int a[n];
  100. cout<<"Enter the elements: "<<endl;
  101. for(int i=0 ; i<n;i++){
  102. cin>>a[i];
  103. }
  104. Tree(a,n);
  105.  
  106.  
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement