Postorder Traversal

Postorder traversal is accessing left then right then root

 

#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 postorder(Node *node)
{
  if(node==NULL) return;

  // Accessing left
  postorder(node->left);

  // Accessing right
  postorder(node->right);

  cout<<node->data<<" ";
}

int main()
{
  Node *root = createNode(3);

  root->left = createNode(9);
  root->right = createNode(20);
  
  root->right->left = createNode(15);
  root->right->right = createNode(7);

  postorder(root);
  return 0;
}

No comments:

If you have any doubt or suggestion let me know in comment section.

Powered by Blogger.