(82). 27.2. BINARY TREE TRAVERSAL (PREORDER , INORDER , POSTORDER TRAVERSAL) - anishsingh90/Data_Structure_And_Algorithm_In_Cpp_github.io GitHub Wiki
//BINARY TREE STRUCTURE CODE #include <bits/stdc++.h> using namespace std;
struct Node{ int data; struct Node* left; struct Node* right;
Node(int val){
data = val;
left = NULL;
right = NULL;
}
};
//Preorder Traversal void preorder(struct Node* root){ if(root == NULL){ return; }
cout << root->data <<" ";
preorder(root->left);
preorder(root->right);
}
//Inorder Traversal void inorder(struct Node* root){ if(root == NULL){ return; }
inorder(root->left);
cout << root->data <<" ";
inorder(root->right);
}
//Postorder Traversal void postorder(struct Node* root){ if(root == NULL){ return; }
postorder(root->left);
postorder(root->right);
cout << root->data <<" ";
}
int main(){ struct Node* root = new Node(1); //root root->left = new Node(2); //left node of root root->right = new Node(3); //right node of root
root->left->left = new Node(4); //left node of left root
root->left->right = new Node(5); //right node of left root
root->right->left = new Node(6); //left node of right root
root->right->right = new Node(7); // right node of right root
cout << "Preorder Traversal: ";
preorder(root);
cout << endl;
cout << "Inorder Traversal: ";
inorder(root);
cout << endl;
cout << "Postorder Traversal: ";
postorder(root);
return 0;
}
/* OUTPUT: Preorder Traversal: 1 2 4 5 3 6 7 Inorder Traversal: 4 2 5 1 6 3 7 Postorder Traversal: 4 5 2 6 7 3 1 */