39: Perform a preorder traversal of a binary tree.
⏳⌚ 00:00:00

Question:-

Perform a preorder traversal of a binary tree.
Example 1:
Input:
according to the question
Output:
Preorder traversal of binary tree is:
1 2 4 5 3 6

Steps to solve:-

1. struct Node:-
This is the definition of a structure representing a binary tree node. Each node has an integer data value, a left child pointer, and a right child pointer. The constructor for the Node structure sets the data value and initializes the child pointers to NULL.
2. void printPreorder(struct Node* node):-
This is a recursive function to perform a preorder traversal of a binary tree. Preorder traversal means visiting the root node first, followed by the left subtree, and then the right subtree. The function takes a pointer to a Node as an argument.
3. int main():-
The main function is the entry point of the program. Inside main, a binary tree is created, and the printPreorder function is called to print the preorder traversal of the tree.
4. Creating the binary tree:-
In main, a binary tree is created with the following structure:
Root node (with data 1) Left child of the root (with data 2) Left child of node 2 (with data 4) Right child of node 2 (with data 5) Right child of the root (with data 3) Right child of node 3 (with data 6) Printing the preorder traversal: After constructing the binary tree, the printPreorder function is called with the root node as an argument to print the preorder traversal. The preorder traversal output is displayed, showing the order in which the nodes are visited.

solution->

View Code 1
Time Complexity = O(n)
Space Complexity = O(1)