Preorder Tree Traversal

Preorder Traversal:

   1. Visit the root.
   2. Traverse the left subtree, i.e., call Preorder(left-subtree)
   3. Traverse the right subtree, i.e., call Preorder(right-subtree)
Example: Preorder traversal for the given progran 1 2 4 5 3.

#include<stdio.h>
#include<stdlib.h>

struct node{

 int data;
 struct node *left;
 struct node *right;
};

//create new node when function CreateNode Called

struct node *CreateNode(int data)   //function to create new node & returning a node so return type is struct
{

struct node *new_node=(struct node*)malloc(sizeof(struct node));  //Allocate memory to new node

new_node->data=data;

new_node->left=NULL;
new_node->right=NULL;

return new_node;
}

void PreorderTraversal(struct node *root)
{

if(root==NULL)
return;

printf("%d\t",root->data);
PreorderTraversal(root->left);
PreorderTraversal(root->right);

}

main()
{

struct node *root;
root=CreateNode(1);

root->left=CreateNode(2);
root->right=CreateNode(3);

root->left->left=CreateNode(4);
root->right->right=CreateNode(5);

printf("\nPreorde traversal is :\t");
PreorderTraversal(root);

}

Related Posts