Preorder Traversal
Postorder traversal is accessing root then left then right
Related : Inorder, postorder and levelorder traversal.
Also check : Tree Data Structure
#include <bits/stdc++.h> using namespace std; class Node { public: int data; Node *left,*right; }; Node *createNode(int new_data) { Node *new_node=new Node(); new_node->data=new_data; new_node->left=NULL; new_node->right=NULL; return new_node; } void preorder(Node *node) { if(node==NULL) return; // Accessing root cout<<node->data<<" "; // Accessing left postorder(node->left); // Accessing right postorder(node->right); } int main() { Node *root = createNode(3); root->left = createNode(9); root->right = createNode(20); root->right->left = createNode(15); root->right->right = createNode(7); preorder(root); return 0; }
No comments:
If you have any doubt or suggestion let me know in comment section.