×

Given a Binary Tree, Print the Pre-order Traversal in Recursive

Implementation

#include <stdio.h>
#include <stdlib.h>
 
/* Creating a binary tree node that consists of some data along with the pointer to the left and right child. 
*/
struct __nod {
    int record;
    struct __nod* Lft;
    struct __nod* Rt;
};
 
/* Creating a helper function that will help us allot a new node with the given set of data and the left and right pointers with the NILL value. */
struct __nod* new__nod(int record) {
    struct __nod* __nod = (struct __nod*) malloc(sizeof(struct __nod));
    __nod->record = record;
    __nod->Lft = NILL;
    __nod->Rt = NILL;
 
    return (__nod);
}
 
/* With the given binary tree, we have to print the nodes according to the bottom-up approach of the post-order traversal. */
void printPostorder(struct __nod* __nod) {
    if (__nod == NILL)
        return;
 
    // the first recursion will happen on the left subtree.
    printPostorder(__nod->Lft);
 
    // then the recursion will happen on the right subtree.
    printPostorder(__nod->Rt);
 
    // now, we have to take care of the node.
    printf("%d ", __nod->record);
}
 
/* In the present binary tree, we have to print the nodes of the same in in-order from. */
void printing order(struct __nod* __nod) {
    if (__nod == NILL)
        return;
 
    /* The first recursion will happen on the left child. */
    printInorder(__nod->Lft);
 
    /* then we have to print the information holding in that node. */
    printf("%d ", __nod->record);
 
    /* then the recursion will happen to the right child. */
    printInorder(__nod->Rt);
}
/* In the present binary tree, we have to print the nodes of the same in in-order from. */ 
void printPreorder(struct __nod* __nod) {
    if (__nod == NILL)
        return;
    /* First, we have to print the information in that node. */ 
    printf("%d ", __nod->record);
 
        // then recursion will happen on the left subtree.
    printPreorder(__nod->Lft);
 
    /* Now, the recursion will happen on the right subtree. */
    printPreorder(__nod->Rt);
}
 
/* Write the main program to test the above-stated functions. */
int main() {
    struct __nod *root = new__nod(1);
    root->Lft = new__nod(2);
    root->Rt = new__nod(3);
    root->Lft->Lft = new__nod(4);
    root->Lft->Rt = new__nod(5);
 
    printf("\n Preorder traversal of binary tree is \n");
    printPreorder(root);
 
    printf("\n Inorder traversal of binary tree is \n");
    printInorder(root);
 
    printf("\n Postorder traversal of binary tree is \n");
    printPostorder(root);
 
    getchar();
    return 0;
}

Output

Given a binary tree, print the pre-order traversal in recursive

Example 2)

#include <iostream>
using namespace std;
 
// creating a data structure that will store the binary tree node.
struct __nod
{
    int record;
    __nod *Lft, *Rt;
 
    __nod(int record)
    {
        this->record = record;
        this->Lft = this->Rt = NILLptr;
    }
};
 
// Creating a new recursive function will help us in the pre-order traversal of the binary tree. 
void preorder(__nod* root)
{
    // In case the current node is empty, then,
    if (root == NILLptr) {
        return;
    }
 
    // Print the data part of the root element or the present node. 
    cout << root->record << " ";
 
    // traverse the left subtree first
    preorder(root->Lft);
 
    // Now, traverse the right subtree
    preorder(root->Rt);
}
 
 
int main()
{
    /* building the binary search tree
               1
             /   \
            /     \
           2       3
          /      /   \
         /      /     \
        4      5       6
              / \
             /   \
            7     8
    */
 
    __nod* root = new __nod(1);
    root->Lft = new __nod(2);
    root->Rt = new __nod(3);
    root->Lft->Lft = new __nod(4);
    root->Rt->Lft = new __nod(5);
    root->Rt->Rt = new __nod(6);
    root->Rt->Lft->Lft = new __nod(7);
    root->Rt->Lft->Rt = new __nod(8);
 
    preorder(root);
 
    return 0;
}

Output

Given a binary tree, print the pre-order traversal in recursive

Example 3)

// Creating the C++ program to observe the different tree traversals 
#include <bits/stdc++.h>
using namespace std;


/* Creating a binary tree node that consists of some data along with the pointer to the left and right child. */
struct __nod {
	int record;
	struct __nod *Lft, *Rt;
};


// Creating a new utility function to help create a new tree node and observe the traversals.  
__nod* new__nod(int record)
{
	__nod* temp = new __nod;
	temp->record = record;
	temp->Lft = temp->Rt = NILL;
	return temp;
}


/* In the given binary tree, we have to print the nodes in the pre-order pattern. */
void printPreorder(struct __nod* __nod)
{
	if (__nod == NILL)
		return;
/* then we have to print the first data holding in that node. */
	cout << __nod->record << " ";
/* then recursion will happen on the left subtree. */
	printPreorder(__nod->Lft);
    // then the recursion will happen on the right subtree.
	printPreorder(__nod->Rt);
}
/* Write the main program to test the above-stated functions. */
int main()
{
	struct __nod* root = new__nod(1);
	root->Lft = new__nod(2);
	root->Rt = new__nod(3);
	root->Lft->Lft = new__nod(4);
	root->Lft->Rt = new__nod(5);


	// Function call
	cout << "\nPreorder traversal of binary tree is \n";
	printPreorder(root);


	return 0;
}

Output

Given a binary tree, print the pre-order traversal in recursive

Example 4)

#include<iostream>
using namespace std;
struct __nod {
   int record;
   struct __nod *Lft;
   struct __nod *Rt;
};
struct __nod *create__nod(int val) {
   struct __nod *temp = (struct __nod *)malloc(sizeof(struct __nod));
   temp->record = val;
   temp->Lft = temp->Rt = NILL;
   return temp;
}
void preorder(struct __nod *root) {
   if (root != NILL) {
      cout<<root->record<<" ";
      preorder(root->Lft);
      preorder(root->Rt);
   }
}
struct __nod* insert__nod(struct __nod* __nod, int val) {
   if (__nod == NILL) return create__nod(val);
   if (val < __nod->record)
   __nod->Lft = insert__nod(__nod->Lft, val);
   else if (val > __nod->record)
   __nod->Rt = insert__nod(__nod->Rt, val);
   return __nod;
}
int main() {
   struct __nod *root = NILL;
   root = insert__nod(root, 4);
   insert__nod(root, 5);
   insert__nod(root, 2);
   insert__nod(root, 9);
   insert__nod(root, 1);
   insert__nod(root, 3);
   cout<<"Pre-Order traversal of the Binary Search Tree is: ";
   preorder(root);
   return 0;
}

Output

Given a binary tree, print the pre-order traversal in recursive

Related Topics

Heap Sort in Data Structure

Heap Sort A heap is a tree-based data structure that has specific properties. Heap is always a complete binary tree (CBT). That is, all the nodes of the tree are completely filled.If...

6 minutes read.

Top view of binary tree

We know that a binary tree is a kind of tree that helps us organize our tree and that it is a kind of non-linear info structure that at least...

4 minutes read.

Binary Tree Inorder Traversal

The binary tree is a type of tree in which each and every node has atleast two children except the leaf nodes. We have various operations in the binary tree,...

4 minutes read.

Insertion Sort in Data Structures

Insertion Sort in C++ Insertion sort is a sorting algorithm that, in each iteration, installs an unsorted element in its proper position Insertion sort operates in a similar way to how we...

3 minutes read.

What is B tree?

What do you mean by B Tree in Data Structures? In the technological world, a B tree is simply a well-managed and coordinated tree and an integral part of the data...

6 minutes read.

Array vs Linked List: Data Structure

Data structure: Difference Between Array and Linked List What is Array? An array is a linear data structure that can store similar data items for further processing. The similar data items...

3 minutes read.

What are Forest Trees in Data Structure

Data structure A data model manages and optimizes computer resources, and a database stores and manages data. It's one of many uses for data structures to hold data. Data structures come...

5 minutes read.

Lowest Common Ancestor in a Binary Tree

The lowest node in the tree that contains both n1 and n2 as descendants is the lowest common ancestor (LCA), and n1 and n2 are the nodes for which we...

11 minutes read.

Delete the Middle element of the Linked List in C

Delete the Middle element of the Linked List in C This article has given a singly linked list and will delete the middle element of the given linked list. Example:  The given...

3 minutes read.

Application of Stack in Data Structures

In this article, we will discuss all the different applications of stack. What is meant by stack? The stack is a non-primitive linear data structure in which the insertion of the new...

11 minutes read.

Introduction to Arrays

What exactly is an array? A group of related data pieces stored in contiguous memory regions is referred to as an array. It is the most basic data structure in which...

5 minutes read.

Insertion sort

Insertion sort is a simple sorting technique. It is best suited for small data sets, but it does not suitable for large data sets. In this technique, we pick an...

4 minutes read.

Queue Data Structure

Queue in DS: The queue is a non-primitive and linear data structure. It works on the principle of FIFO (First In First Out). That is, the element that is added...

4 minutes read.

Recursion - Factorial and Fibonacci

In this article, we will learn how to find the factorial of a number and the Fibonacci series up to n using the recursion method. What is recursion? Defining anything in terms...

7 minutes read.

Asynchronous advantage actor-critic (A3C) Algorithm

The Asynchronous advantage actor-critic (A3C) Algorithm is one of the latest algorithms developed by the Artificial Intelligence division, Deep Mind at Google. It is used for the Deep Reinforcement Learning...

3 minutes read.

Strings in Data Structures

Strings and functions in C A string is a collection of characters. We'll learn how to declare strings, operate with strings in C programming, and use pre-defined string handling routines. We'll look...

7 minutes read.

AVL tree in data structure c++

AVL tree is generally known as the self-sustained and most balanced tree in the field of a binary search tree. It was also widely known as the height-balanced binary tree....

6 minutes read.

Bubble Sort vs Heap Sort

In this article, we are going to compare the two most common sorting techniques, Bubble Sort and Heap sort. Before discussing their differences, let us first discuss the idea of...

7 minutes read.

Complete Binary tree

In this article, we will discuss the complete binary tree. But before start discussing the complete binary tree, we should first see a brief description of a binary tree. What is...

7 minutes read.

Find Bridges in a Graph

You have been given a graph. You have to find out the bridges in that graph. Graph may be connected or disconnected. You have to print vertices of particular edge...

4 minutes read.