The Wayback Machine - https://web.archive.org/web/20241001010723/https://www.geeksforgeeks.org/preorder-traversal-of-binary-tree/
Open In App

Preorder Traversal of Binary Tree

Last Updated : 19 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Preorder traversal is defined as a type of tree traversal that follows the Root-Left-Right policy where:

  • The root node of the subtree is visited first.
  • Then the left subtree  is traversed.
  • At last, the right subtree is traversed.
How preorder traversal works

Algorithm for Preorder Traversal of Binary Tree

The algorithm for preorder traversal is shown as follows:

Preorder(root):

  1. If root is NULL then return
  2. Process root (For example, print root’s data)
  3. Preorder (root -> left)
  4. Preorder (root -> right)

Examples of Preorder Traversal

Input : …….A
…………../ …….\
………..B ………..C
Output : ABC

Input :…….A
…………../ …….\
………..B ………..C
……../……\
……D……..E
Output : ABDEC

Input : A
Output : A

Input : NULL
Output :
Output is empty in this case.

Program to Implement Preorder Traversal of Binary Tree

Below is the code implementation of the preorder traversal:

C++
// C++ program for preorder traversals

#include <bits/stdc++.h>
using namespace std;

// Structure of a Binary Tree Node
struct Node {
    int data;
    struct Node *left, *right;
    Node(int v)
    {
        data = v;
        left = right = nullptr;
    }
};

// Function to print preorder traversal
void printPreorder(struct Node* node)
{
    if (node == nullptr)
        return;

    // Deal with the node
    cout << node->data << " ";

    // Recur on left subtree
    printPreorder(node->left);

    // Recur on right subtree
    printPreorder(node->right);
}

// Driver code
int main()
{
    struct Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    root->right->right = new Node(6);

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

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

// Structure of a Binary Tree Node
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

// Function to create a new node
struct Node* newNode(int v) {
    struct Node* node =
      (struct Node*)malloc(sizeof(struct Node));
    node->data = v;
    node->left = NULL;
    node->right = NULL;
    return node;
}

// Function to print preorder traversal
void printPreorder(struct Node* node) {
    if (node == NULL)
        return;

    // Deal with the node
    printf("%d ", node->data);

    // Recur on left subtree
    printPreorder(node->left);

    // Recur on right subtree
    printPreorder(node->right);
}

// Driver code
int main() {
    struct Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->right = newNode(6);

    // Function call
    printf("Preorder traversal of binary tree is:\n");
    printPreorder(root);
    printf("\n");

    return 0;
}
Java
// Java program for preorder traversals

class Node {
    int data;
    Node left, right;

    public Node(int item) {
        data = item;
        left = right = null;
    }
}

class BinaryTree {
    Node root;

    BinaryTree() {
        root = null;
    }

    // Function to print preorder traversal
    void printPreorder(Node node) {
        if (node == null)
            return;

        // Deal with the node
        System.out.print(node.data + " ");

        // Recur on left subtree
        printPreorder(node.left);

        // Recur on right subtree
        printPreorder(node.right);
    }

    // Driver code
    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();

        // Constructing the binary tree
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);
        tree.root.right.right = new Node(6);

        // Function call
        System.out.println("Preorder traversal of binary tree is: ");
        tree.printPreorder(tree.root);
    }
}
Python
# Python program for preorder traversals

# Structure of a Binary Tree Node
class Node:
    def __init__(self, v):
        self.data = v
        self.left = None
        self.right = None

# Function to print preorder traversal
def printPreorder(node):
    if node is None:
        return

    # Deal with the node
    print(node.data, end=' ')

    # Recur on left subtree
    printPreorder(node.left)

    # Recur on right subtree
    printPreorder(node.right)


# Driver code
if __name__ == '__main__':
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.right.right = Node(6)

    # Function call
    print("Preorder traversal of binary tree is:")
    printPreorder(root)
C#
// C# program for preorder traversals
using System;

// Structure of a Binary Tree Node
public class Node {
    public int data;
    public Node left, right;

    public Node(int v)
    {
        data = v;
        left = right = null;
    }
}

// Class to print preorder traversal
public class BinaryTree {
    // Function to print preorder traversal
    public static void printPreorder(Node node)
    {
        if (node == null)
            return;

        // Deal with the node
        Console.Write(node.data + " ");

        // Recur on left subtree
        printPreorder(node.left);

        // Recur on right subtree
        printPreorder(node.right);
    }

    // Driver code
    public static void Main()
    {
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.right = new Node(6);

        // Function call
        Console.WriteLine(
            "Preorder traversal of binary tree is: ");
        printPreorder(root);
    }
}

// This code is contributed by Susobhan Akhuli
JavaScript
// Structure of a Binary Tree Node
class Node {
  constructor(v) {
    this.data = v;
    this.left = null;
    this.right = null;
  }
}

// Function to print preorder traversal
function printPreorder(node) {
  if (node === null) {
    return;
  }

  // Deal with the node
  console.log(node.data);

  // Recur on left subtree
  printPreorder(node.left);

  // Recur on right subtree
  printPreorder(node.right);
}

// Driver code
function main() {
  const root = new Node(1);
  root.left = new Node(2);
  root.right = new Node(3);
  root.left.left = new Node(4);
  root.left.right = new Node(5);
  root.right.right = new Node(6);

  // Function call
  console.log("Preorder traversal of binary tree is:");
  printPreorder(root);
}

main();

Output
Preorder traversal of binary tree is: 
1 2 4 5 3 6 

Complexity Analysis:

Time Complexity: O(N) where N is the total number of nodes. Because it traverses all the nodes at least once.
Auxiliary Space: 

  • O(1) if no recursion stack space is considered. 
  • Otherwise, O(h) where h is the height of the tree
  • In the worst case, h can be the same as N (when the tree is a skewed tree)
  • In the best case, h can be the same as logN (when the tree is a complete tree)

How does Preorder Traversal of Binary Tree work?

Consider the following tree:

Example of Binary Tree

Example of Binary Tree

If we perform a preorder traversal in this binary tree, then the traversal will be as follows:

Step 1: At first the root will be visited, i.e. node 1.

Node 1 is visited

Node 1 is visited

Step 2: After this, traverse in the left subtree. Now the root of the left subtree is visited i.e., node 2 is visited.

Node 2 is visited

Node 2 is visited

Step 3: Again the left subtree of node 2 is traversed and the root of that subtree i.e., node 4 is visited.

Node 4 is visited

Node 4 is visited

Step 4: There is no subtree of 4 and the left subtree of node 2 is visited. So now the right subtree of node 2 will be traversed and the root of that subtree i.e., node 5 will be visited.

Node 5 is visited

Node 5 is visited

Step 5: The left subtree of node 1 is visited. So now the right subtree of node 1 will be traversed and the root node i.e., node 3 is visited.

Node 3 is visited

Node 3 is visited

Step 6: Node 3 has no left subtree. So the right subtree will be traversed and the root of the subtree i.e., node 6 will be visited. After that there is no node that is not yet traversed. So the traversal ends.

The complete tree is visited

The complete tree is visited

So the order of traversal of nodes is 1 -> 2 -> 4 -> 5 -> 3 -> 6.

Use cases of Preorder Traversal:

Some use cases of preorder traversal are:

  • It is also useful to get the prefix expression from an expression tree.
  • Or any other case where we wish to traverse the root node first.

Related Articles:



Similar Reads

Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
Given two arrays that represent Preorder traversals of a full binary tree and its mirror tree, we need to write a program to construct the binary tree using these two Preorder traversals.A Full Binary Tree is a binary tree where every node has either 0 or 2 children. Note: It is not possible to construct a general binary tree using these two traver
12 min read
Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T. For Example: Input: Tree T - 1 / \ 2 3 / \ / \ 4 5 6 7 Tree S - 2 / \ 4 5 Output: YES Explanation: The above tree is the subtree of the tree T, Hence the output is YES Approach: The idea is to traverse both the tree in Pre-order Traversal and check for each
11 min read
Find postorder traversal of BST from preorder traversal
Given an array representing preorder traversal of BST, print its postorder traversal. Examples: Input : 40 30 35 80 100 Output : 35 30 100 80 40 Input : 40 30 32 35 80 90 100 120 Output : 35 32 30 120 100 90 80 40 Prerequisite: Construct BST from given preorder traversal Simple Approach: A simple solution is to first construct BST from a given preo
9 min read
Modify a binary tree to get preorder traversal using right pointers only
Given a binary tree. Modify it in such a way that after modification you can have a preorder traversal of it using only the right pointers. During modification, you can use right as well as left pointers. Examples: Input : 10 / \ 8 2 / \ 3 5 Output : 10 \ 8 \ 3 \ 5 \ 2 Explanation : The preorder traversal of given binary tree is 10 8 3 5 2. Method
15 min read
Find n-th node in Preorder traversal of a Binary Tree
Given a Binary tree and a number N, write a program to find the N-th node in the Preorder traversal of the given Binary tree. Prerequisite: Tree Traversal Examples: Input: N = 4 11 / \ 21 31 / \ 41 51 Output: 51 Explanation: Preorder Traversal of given Binary Tree is 11 21 41 51 31, so 4th node will be 51. Input: N = 5 25 / \ 20 30 / \ / \ 18 22 24
6 min read
Preorder, Postorder and Inorder Traversal of a Binary Tree using a single Stack
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order iteratively using only one stack traversal. Examples: Input: Output:Preorder Traversal: 1 2 3Inorder Traversal: 2 1 3Postorder Traversal: 2 3 1 Input: Output:Preorder traversal: 1 2 4 5 3 6 7Inorder traversal: 4 2 5 1 6 3 7Post-order tr
13 min read
Construct a Perfect Binary Tree from Preorder Traversal
Given an array pre[], representing the Preorder traversal of a Perfect Binary Tree consisting of N nodes, the task is to construct a Perfect Binary Tree from the given Preorder Traversal and return the root of the tree. Examples: Input: pre[] = {1, 2, 4, 5, 3, 6, 7}Output: 1 / \ / \ 2 3 / \ / \ / \ / \ 4 5 6 7 Input: pre[] = {1, 2, 3}Output: 1 / \
11 min read
Check if a given array can represent Preorder Traversal of Binary Search Tree
Given an array of numbers, return true if given array can represent preorder traversal of a Binary Search Tree, else return false. Expected time complexity is O(n). Examples: Input: pre[] = {2, 4, 3} Output: true Given array can represent preorder traversal of below tree 2 \ 4 / 3 Input: pre[] = {2, 4, 1} Output: false Given array cannot represent
15 min read
Vertical Traversal of a Binary Tree using Preorder
Given a binary tree, print it vertically. The following examples illustrate the vertical order traversal.   Input:         1                  /    \                 2      3               / \   /   \             4   5  6   7                         /  \                        8    9  Output:  421 5 63 879 Brute Force Approach : O(n^2)We traverse th
15 min read
Preorder Traversal of N-ary Tree Without Recursion
Given an n-ary tree, print preorder traversal of it. Example : Preorder traversal of below tree is A B K N M J F D G E C H I L The idea is to use stack like iterative preorder traversal of binary tree. Create an empty stack to store nodes. Push the root node to the stack. Run a loop while the stack is not empty Pop the top node from stack. Print th
7 min read
Construct a special tree from given preorder traversal
Given an array 'pre[]' that represents Preorder traversal of a special binary tree where every node has either 0 or 2 children. One more array 'preLN[]' is given which has only two possible values 'L' and 'N'. The value 'L' in 'preLN[]' indicates that the corresponding node in Binary Tree is a leaf node and value 'N' indicates that the correspondin
15+ min read
Construct the full k-ary tree from its preorder traversal
Given an array that contains the preorder traversal of the full k-ary tree, construct the full k-ary tree and print its postorder traversal. A full k-ary tree is a tree where each node has either 0 or k children. Examples: Input : preorder[] = {1, 2, 5, 6, 7, 3, 8, 9, 10, 4} k = 3 Output : Postorder traversal of constructed full k-ary tree is: 5 6
10 min read
Check if given inorder and preorder traversals are valid for any Binary Tree without building the tree
cGiven two arrays pre[] and in[] representing the preorder and inorder traversal of the binary tree, the task is to check if the given traversals are valid for any binary tree or not without building the tree. If it is possible, then print Yes. Otherwise, print No. Examples: Input: pre[] = {1, 2, 4, 5, 7, 3, 6, 8}, in[] = {4, 2, 5, 7, 1, 6, 8, 3}Ou
15+ min read
Level order traversal of Binary Tree using Morris Traversal
Given a binary tree, the task is to traverse the Binary Tree in level order fashion.Examples: Input: 1 / \ 2 3 Output: 1 2 3 Input: 5 / \ 2 3 \ 6 Output: 5 2 3 6 Approach: The idea is to use Morris Preorder Traversal to traverse the tree in level order traversal.Observations: There are mainly two observations for the traversal of the tree using Mor
11 min read
Pre Order, Post Order and In Order traversal of a Binary Tree in one traversal | (Using recursion)
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order in one iteration. Examples: Input: Output: Pre Order: 1 2 4 5 3 6 7 Post Order: 4 5 2 6 7 3 1 In Order: 4 2 5 1 6 3 7 Input: Output: Pre Order: 1 2 4 8 12 5 9 3 6 7 10 11 Post Order: 12 8 4 9 5 2 6 10 11 7 3 1 In Order: 8 12 4 2 9 5 1 6
9 min read
Construct BST from given preorder traversal using Stack
Given preorder traversal of a binary search tree, construct the BST.For example, if the given traversal is {10, 5, 1, 7, 40, 50}, then the output should be root of following tree. 10 / \ 5 40 / \ \ 1 7 50 We have discussed O(n^2) and O(n) recursive solutions in the previous post. Following is a stack based iterative solution that works in O(n) time
13 min read
Number of elements smaller than root using preorder traversal of a BST
Given a preorder traversal of a BST. The task is to find the number of elements less than root. Examples: Input: preorder[] = {3, 2, 1, 0, 5, 4, 6} Output: 3 Input: preorder[] = {5, 4, 3, 2, 1} Output: 4 For a binary search tree, a preorder traversal is of the form: root, { elements in left subtree of root }, { elements in right subtree of root } S
9 min read
Find Leftmost and Rightmost node of BST from its given preorder traversal
Given a preorder sequence of the binary search tree of N nodes. The task is to find its leftmost and rightmost nodes. Examples: Input : N = 5, preorder[]={ 3, 2, 1, 5, 4 } Output : Leftmost = 1, Rightmost = 5 The BST constructed from this preorder sequence would be: 3 / \ 2 5 / / 1 4 Leftmost Node of this tree is equal to 1 Rightmost Node of this t
5 min read
Construct BST from given preorder traversal using Sorting
Given preorder traversal of a binary search tree, construct the BST.For example, if the given traversal is {10, 5, 1, 7, 40, 50}, then the output should be root of following tree. 10 / \ 5 40 / \ \ 1 7 50 We have discussed methods to construct binary search tree in previous posts.Here is another method to construct binary search tree when given pre
10 min read
Print Postorder traversal from given Inorder and Preorder traversals
AuxiliaryGiven Inorder and Preorder traversals of a binary tree, print Postorder traversal. Example: Input: Inorder traversal in[] = {4, 2, 5, 1, 3, 6} Preorder traversal pre[] = {1, 2, 4, 5, 3, 6} Output: Postorder traversal is {4, 5, 2, 6, 3, 1} Traversals in the above example represents following tree 1 / \ 2 3 / \ \ 4 5 6Recommended PracticePos
15+ min read
Morris traversal for Preorder
Using Morris Traversal, we can traverse the tree without using stack and recursion. The algorithm for Preorder is almost similar to Morris traversal for Inorder. 1...If left child is null, print the current node data. Move to right child. ....Else, Make the right child of the inorder predecessor point to the current node. Two cases arise: .........
10 min read
Iterative Preorder Traversal
Given a Binary Tree, write an iterative function to print the Preorder traversal of the given binary tree.Refer to this for recursive preorder traversal of Binary Tree. To convert an inherently recursive procedure to iterative, we need an explicit stack. Following is a simple stack based iterative process to print Preorder traversal. Create an empt
15+ min read
Construct BST from Preorder Traversal
Given the preorder traversal of a binary search tree, construct the BST. Examples: Input: {10, 5, 1, 7, 40, 50}Output: 10 / \ 5 40 / \ \ 1 7 50Explanation: The constructed tree is BST and if we do preorder traversal of it, we get the same array Input: {1, 2]Output: 1 \ 2 Input: {2, 1]Output: 2 / 1 Table of Content Naive - One by One Insert Better -
15+ min read
Construct Full Binary Tree from given preorder and postorder traversals
Given two arrays that represent preorder and postorder traversals of a full binary tree, construct the binary tree. Full Binary Tree is a binary tree where every node has either 0 or 2 children. Illustration: Following are examples of Full Trees. 1 / \ 2 3 / \ / \ 4 5 6 7 1 / \ 2 3 / \ 4 5 / \ 6 7 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 It is not possibl
14 min read
Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
Given Preorder traversal of a Binary Search Tree. Then the task is to print leaf nodes of the Binary Search Tree from the given preorder. Examples : Input : preorder[] = {890, 325, 290, 530, 965}; Output : 290 530 965 Tree represented is, 890 / \ 325 965 / \ 290 530 Input : preorder[] = { 3, 2, 4 }; Output : 2 4 In this post, a simple recursive sol
5 min read
Modify Binary Tree by replacing each node with the sum of its Preorder Predecessor and Successor
Given a binary tree consisting of N nodes, the task is to replace each node in the binary tree with the sum of its preorder predecessor and preorder successor. Examples: Input: 2 / \ 3 4 / \ / \ 6 5 7 8 Output: 3 / \ 8 12 / \ / \ 8 10 12 7 Explanation: For Node 2: Preorder predecessor = 0 (as preorder predecessor is not present), preorder successor
13 min read
Calculate depth of a full Binary tree from Preorder
Given preorder of a binary tree, calculate its depth(or height) [starting from depth 0]. The preorder is given as a string with two possible characters. 'l' denotes the leaf'n' denotes internal node The given tree can be seen as a full binary tree where every node has 0 or two children. The two children of a node can 'n' or 'l' or mix of both. Exam
5 min read
Preorder predecessor of a Node in Binary Tree
Given a binary tree and a node in the binary tree, find Preorder predecessor of the given node. Examples: Consider the following binary tree 20 / \ 10 26 / \ / \ 4 18 24 27 / \ 14 19 / \ 13 15Input: 4Output: 10Preorder traversal of given tree is 20, 10, 4, 18, 14, 13, 15, 19, 26, 24, 27.Input: 19Output: 15A simple solution is to first store Preorde
8 min read
Leaf nodes from Preorder of a Binary Search Tree
Given a Preorder traversal of a Binary Search Tree. The task is to print leaf nodes of the Binary Search Tree from the given preorder. Examples: Input : preorder[] = {890, 325, 290, 530, 965}; Output : 290 530 965 Explanation : Tree represented is, 890 / \ 325 965 / \ 290 530 Input : preorder[] = { 3, 2, 4 }; Output : 2 4Recommended PracticePrint l
15 min read
Preorder Successor of a Node in Binary Tree
Given a binary tree and a node in the binary tree, find the preorder successor of the given node. It may be assumed that every node has a parent link. Examples: Consider the following binary tree 20 / \ 10 26 / \ / \ 4 18 24 27 / \ 14 19 / \ 13 15 Input : 4 Output : 18 Preorder traversal of given tree is 20, 10, 4, 18, 14, 13, 15, 19, 26, 24, 27. I
9 min read
Practice Tags :