Saturday, June 19, 2021
Home coding Write a program to traverse tree using Preorder traversal.

Write a program to traverse tree using Preorder traversal.

Given a tree ,we have to traverse a tree using preorder traversal and print the result.

So what is Preorder Traversal?

In this traversal we follow root,left,right approach.

Logic:

step 1-  print root value.
step 2- traverse left subtree 
step 3- traverse right subtree.

void preorder(node *root)
{
if(root==NULL)
{
return;
}
cout<<root->data<<" "
preorder(root->left);
preorder(root->right);
}

Time Complexity:O(N)

Space Complexity:O(N)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments