In: Computer Science
Traversal tree program in c/c++
Code:
#include <iostream>
using namespace std;
// struct Node
struct Node
{
int data;
struct Node*left;
struct Node*right;
//constructor
Node(int val)
{
this->data=val;
left=NULL;right=NULL;
}
};
//Requested function to traverse tree
void preorderTraverse(Node* A)
{
//base case
if(A==NULL)return;
//printing data of Node
cout<<A->data<<" ";
//if left node exist traverse left
if(A->left!=NULL)preorderTraverse(A->left);
//if right node exist traverse right
if(A->right!=NULL)preorderTraverse(A->right);
}
int main()
{
//sample tree to check working of function
struct Node *root=new Node(3);
root->left=new Node(7);
root->right=new Node(4);
root->left->left=new Node(9);
root->left->right=new Node(5);
root->right->left=new Node(11);
// 3
// / \
// 7 4
// / \ /
// 9 5 11
//calling traverse function
preorderTraverse(root);
}
Sample Output:
NOTE: If you got any help from this article please UPVOTE and if you hace any query please do mention in comments...