Open In App

Tree Traversal Techniques

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

Tree Traversal techniques include various ways to visit all the nodes of the tree. Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. In this article, we will discuss about all the tree traversal techniques along with their uses.

Tree-Traversal-Techniques-(1)

Tree Traversal Meaning:

Tree Traversal refers to the process of visiting or accessing each node of the tree exactly once in a certain order. Tree traversal algorithms help us to visit and process all the nodes of the tree. Since tree is not a linear data structure, there are multiple nodes which we can visit after visiting a certain node. There are multiple tree traversal techniques which decide the order in which the nodes of the tree are to be visited.

Tree Traversal Techniques:

Tree-Traversal-Techniques

A Tree Data Structure can be traversed in following ways:

  • Depth First Search or DFS
    • Inorder Traversal
    • Preorder Traversal
    • Postorder Traversal
  • Level Order Traversal or Breadth First Search or BFS

Inorder Traversal:

Inorder traversal visits the node in the order: Left -> Root -> Right

Preorder-Traversal-of-Binary-Tree

Algorithm for Inorder Traversal:

Inorder(tree)

  • Traverse the left subtree, i.e., call Inorder(left->subtree)
  • Visit the root.
  • Traverse the right subtree, i.e., call Inorder(right->subtree)

Uses of Inorder Traversal:

  • In the case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order.
  • To get nodes of BST in non-increasing order, a variation of Inorder traversal where Inorder traversal is reversed can be used.
  • Inorder traversal can be used to evaluate arithmetic expressions stored in expression trees.

To strengthen your understanding of algorithms and data structures, such as tree traversal techniques , and to excel in technical exams and interviews, check out our comprehensive course, Tech Interview 101 – From DSA to System Design , which covers data structures and algorithms from basic to advanced levels.

Code Snippet for Inorder Traversal:

C++
#include <iostream>
using namespace std;

struct Node {
    int data;
    Node* left;
    Node* right;
    Node(int val) : data(val), left(nullptr), right(nullptr) {}
};

// Function to perform inorder traversal
void inorderTraversal(Node* root) {
  
    // Empty Tree
    if (root == nullptr)
        return;
  
    // Recur on the left subtree
    inorderTraversal(root->left);
 
    // Visit the current node
    cout << root->data << " ";
  
    // Recur on the right subtree
    inorderTraversal(root->right);
}

int 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);
    inorderTraversal(root);
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

// Function to perform inorder traversal
void inorderTraversal(struct Node* root) {
  
    // Empty Tree
    if (root == NULL)
        return;
  
    // Recur on the left subtree
    inorderTraversal(root->left);
  
    // Visit the current node
    printf("%d ", root->data);
  
    // Recur on the right subtree
    inorderTraversal(root->right);
}

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

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);
    printf("Inorder traversal: ");
    inorderTraversal(root);
    printf("\n");
    return 0;
}
Java
class Node {
    int data;
    Node left, right;

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

class GfG {

    // Function to perform inorder traversal
    static void inorderTraversal(Node node) {
      
        // Base case
        if (node == null)
            return;
      
        // Recur on the left subtree
        inorderTraversal(node.left);
      
        // Visit the current node
        System.out.print(node.data + " ");
      
        // Recur on the right subtree
        inorderTraversal(node.right);
    }

    public static void main(String[] args) {
        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);
        inorderTraversal(root);
    }
}
Python
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

# Function to perform inorder traversal
def inorderTraversal(root):
  
    # Base case: if null
    if root is None:
        return
      
    # Recur on the left subtree
    inorderTraversal(root.left)
    
    # Visit the current node
    print(root.data, end=" ")
    
    # Recur on the right subtree
    inorderTraversal(root.right)

    
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
inorderTraversal(root)
C#
using System;

class Node {
    public int data;
    public Node left, right;

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

public class GfG {

    // Function to perform inorder traversal
    static void inorderTraversal(Node node) {
      
        // Base case
        if (node == null)
            return;

        // Recur on the left subtree
        inorderTraversal(node.left);
      
        // Visit the current node
        Console.Write(node.data + " ");
      
        // Recur on the right subtree
        inorderTraversal(node.right);
    }

    public static void Main(string[] args) {
        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);
        inorderTraversal(root);
    }
}
JavaScript
// Define the structure for the Node
class Node {
    constructor(data)
    {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}

// Function to perform inorder traversal
function inorderTraversal(node)
{
    // Base case
    if (node == null)
        return;

    // Recur on the left subtree
    inorderTraversal(node.left);

    // Visit the current node
    console.log(node.data);

    // Recur on the right subtree
    inorderTraversal(node.right);
}

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);

inorderTraversal(root);

Output
4 2 5 1 3 

Time Complexity: O(N)
Auxiliary Space: If we don’t consider the size of the stack for function calls then O(1) otherwise O(h) where h is the height of the tree.

Preorder Traversal:

Preorder traversal visits the node in the order: Root -> Left -> Right

Inorder-Traversal-of-Binary-Tree

Algorithm for Preorder Traversal:

Preorder(tree)

  • Visit the root.
  • Traverse the left subtree, i.e., call Preorder(left->subtree)
  • Traverse the right subtree, i.e., call Preorder(right->subtree)

Uses of Preorder Traversal:

  • Preorder traversal is used to create a copy of the tree.
  • Preorder traversal is also used to get prefix expressions on an expression tree.

Code Snippet for Preorder Traversal:

C++
#include <iostream>
using namespace std;

struct Node {
    int data;
    Node* left;
    Node* right;
    Node(int x) {
       data = x;
       left = right = nullptr;
    }
};

// Function to perform preorder traversal
void preorderTraversal(Node* root) {
    // Base case
    if (root == nullptr)
        return;
  
    // Visit the current node
    cout << root->data << " ";
  
    // Recur on the left subtree
    preorderTraversal(root->left);
  
    // Recur on the right subtree
    preorderTraversal(root->right);
}

int 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);
    preorderTraversal(root);
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

// Function to perform preorder traversal
void preorderTraversal(struct Node* root) {
  
    // Base case
    if (root == NULL)
        return;
  
    // Visit the current node
    printf("%d ", root->data);
  
    // Recur on the left subtree
    preorderTraversal(root->left);
  
    // Recur on the right subtree
    preorderTraversal(root->right);
}

struct Node* newNode(int data) {
    struct Node* node = 
      (struct Node*)malloc(sizeof(struct Node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return node;
}

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);
    preorderTraversal(root);
    return 0;
}
Java
class Node {
    int data;
    Node left, right;
    public Node(int item) {
        data = item;
        left = right = null;
    }
}

public class GfG {

    // Function to perform preorder traversal
    static void preorderTraversal(Node node) {
      
        // Base case
        if (node == null)
            return;
      
        // Visit the current node
        System.out.print(node.data + " ");
      
        // Recur on the left subtree
        preorderTraversal(node.left);
      
        // Recur on the right subtree
        preorderTraversal(node.right);
    }

    public static void main(String[] args) {
        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);
        preorderTraversal(root);
    }
}
Python
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

# Function to perform preorder traversal
def preorderTraversal(root):
  
    # Base case
    if root is None:
        return
      
    # Visit the current node
    print(root.data, end=' ')
    
    # Recur on the left subtree
    preorderTraversal(root.left)
    
    # Recur on the right subtree
    preorderTraversal(root.right)


if __name__ == "__main__":
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    preorderTraversal(root)
C#
using System;

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

class GfG {

    // Function to perform preorder traversal
    static void PreorderTraversal(Node node) {
      
        // Base case
        if (node == null)
            return;
      
        // Visit the current node
        Console.Write(node.data + " ");
      
        // Recur on the left subtree
        PreorderTraversal(node.left);
      
        // Recur on the right subtree
        PreorderTraversal(node.right);
    }

    public static void Main(string[] args) {
        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);
        PreorderTraversal(root);
    }
}
JavaScript
class Node {
    constructor(data)
    {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}

// Function to perform preorder traversal
function preorderTraversal(node)
{
    // Base case
    if (node === null)
        return;

    // Visit the current node
    console.log(node.data + " ");

    // Recur on the left subtree
    preorderTraversal(node.left);

    // Recur on the right subtree
    preorderTraversal(node.right);
}

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);
preorderTraversal(root);

Output
1 2 4 5 3 

Time Complexity: O(N)
Auxiliary Space: If we don’t consider the size of the stack for function calls then O(1) otherwise O(h) where h is the height of the tree.

Postorder Traversal:

Postorder traversal visits the node in the order: Left -> Right -> Root

Postorder-Traversal-of-Binary-Tree

Algorithm for Postorder Traversal:

Algorithm Postorder(tree)

  • Traverse the left subtree, i.e., call Postorder(left->subtree)
  • Traverse the right subtree, i.e., call Postorder(right->subtree)
  • Visit the root

Uses of Postorder Traversal:

  • Postorder traversal is used to delete the tree. See the question for the deletion of a tree for details.
  • Postorder traversal is also useful to get the postfix expression of an expression tree.
  • Postorder traversal can help in garbage collection algorithms, particularly in systems where manual memory management is used.

Code Snippet for Postorder Traversal:

C++
#include <iostream>
using namespace std;

struct Node {
    int data;
    Node* left;
    Node* right;
    Node(int x) {
       data = x;
       left = right = nullptr;
    }
};

// Function to perform postorder traversal
void postorderTraversal(Node* node) {
  
    // Base case
    if (node == nullptr)
        return;
  
    // Recur on the left subtree
    postorderTraversal(node->left);
  
    // Recur on the right subtree
    postorderTraversal(node->right);
  
    // Visit the current node
    cout << node->data << " ";
}

int 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);
    postorderTraversal(root);
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

// Function to perform postorder traversal
void postorderTraversal(struct Node* node) {
  
    // Base case
    if (node == NULL)
        return;
  
    // Recur on the left subtree
    postorderTraversal(node->left);
  
    // Recur on the right subtree
    postorderTraversal(node->right);
  
    // Visit the current node
    printf("%d ", node->data);
}

struct Node* newNode(int data) {
    struct Node* node = 
      (struct Node*)malloc(sizeof(struct Node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return node;
}

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);
    postorderTraversal(root);
    return 0;
}
Java
class Node {
    int data;
    Node left, right;
    public Node(int item) {
        data = item;
        left = right = null;
    }
}

public class GfG {
    static void postorderTraversal(Node node) {
      
        // Base case: 
        if (node == null)
            return;
      
        // Recur on the left subtree
        postorderTraversal(node.left);
      
        // Recur on the right subtree
        postorderTraversal(node.right);
      
        // Visit the current node
        System.out.print(node.data + " ");
    }

    public static void main(String[] args) {
        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);
        postorderTraversal(root);
    }
}
Python
class Node:
    # Constructor to create a new node
    def __init__(self, data):
        # Assign data to this node
        self.data = data
        # Initialize left and right children as None
        self.left = None
        self.right = None

# Function to perform postorder traversal
def postorderTraversal(node):
    # Base case: if the current node is null, return
    if node is None:
        return
    # Recur on the left subtree
    postorderTraversal(node.left)
    # Recur on the right subtree
    postorderTraversal(node.right)
    # Visit the current node
    print(node.data, end=' ')

# Main function
def main():
    # Creating the tree nodes
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)

    # Perform postorder traversal
    print("Postorder traversal: ", end='')
    postorderTraversal(root)
    print()

# Run the main function
if __name__ == "__main__":
    main()
C#
using System;

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

class TreeTraversal {

    // Function to perform postorder traversal
    static void PostorderTraversal(Node node) {
      
        // Base case
        if (node == null)
            return;
      
        // Recur on the left subtree
        PostorderTraversal(node.left);
      
        // Recur on the right subtree
        PostorderTraversal(node.right);
      
        // Visit the current node
        Console.Write(node.data + " ");
    }

    public static void Main(string[] args) {
        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);
        PostorderTraversal(root);
    }
}
JavaScript
class Node {
    constructor(data)
    {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}

// Function to perform postorder traversal
function postorderTraversal(node)
{
    // Base case
    if (node === null)
        return;

    // Recur on the left subtree
    postorderTraversal(node.left);

    // Recur on the right subtree
    postorderTraversal(node.right);

    // Visit the current node
    console.log(node.data);
}

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);
postorderTraversal(root);

Output
4 5 2 3 1 

Level Order Traversal :

Level Order Traversal visits all nodes present in the same level completely before visiting the next level.

Level-Order-Traversal-of-Binary-Tree

Algorithm for Level Order Traversal:

LevelOrder(tree)

  • Create an empty queue Q
  • Enqueue the root node of the tree to Q
  • Loop while Q is not empty
    • Dequeue a node from Q and visit it
    • Enqueue the left child of the dequeued node if it exists
    • Enqueue the right child of the dequeued node if it exists

Uses of Level Order:

Code Snippet for Level Order Traversal:

C++
#include <iostream>
#include <queue>
using namespace std;

struct Node {
    int data;
    Node* left;
    Node* right;
    Node(int x) {
      data = x;
      left = right = nullptr;
    }
};

// Prints level order traversal
void levelOrderTraversal(Node* root) {
    if (!root) return;
    queue<Node*> q;
    q.push(root);
    while (!q.empty()) {
        Node* curr = q.front();
        q.pop();
        cout << curr->data << " ";
        if (curr->left) q.push(curr->left);
        if (curr->right) q.push(curr->right);
    }
}

int 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);
    levelOrderTraversal(root);
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

// Tree Node
struct Node {
    int data;
    struct Node *left;
    struct Node *right;
};

// Queue is implemented using singly 
// Linked List
struct QNode {
    struct Node *tNode;
    struct QNode *next;
};

// Ideally we should not use global variables. We have used here
// to reduce code length. Refer the following link for code 
// without globals
// https://ide.geeksforgeeks.org/online-c-compiler/022957c0-7344-4773-b2b9-8c0695418af1
struct QNode *front = NULL;
struct QNode *rear = NULL;

// The following functions are defined later
// in this code
void enqueue(struct Node *tNode);
struct Node *dequeue();

// Function to do level order traversal of given
// Binary Tree using a Queue
void levelOrderTraversal(struct Node* root) {
    if (root == NULL) return; 

    enqueue(root);
    
    while (front != NULL) {
        struct Node* curr = dequeue();
        printf("%d ", curr->data);
        if (curr->left != NULL) enqueue(curr->left);
        if (curr->right != NULL) enqueue(curr->right);
    }
}

struct Node* newNode(int x) {
    struct Node* node = 
     (struct Node*)malloc(sizeof(struct Node));
    node->data = x;
    node->left = node->right = NULL;
    return node;
}
struct QNode* newQNode(struct Node* tNode) {
    struct QNode* qNode = 
     (struct QNode*)malloc(sizeof(struct QNode));
    qNode->tNode = tNode;
    qNode->next = NULL;
    return qNode;
}
void enqueue(struct Node *tNode) {
    struct QNode* qNode = newQNode(tNode);
    
    if (rear == NULL) {
        front = rear = qNode;
    } else {
        rear->next = qNode;
        rear = qNode;
    }
}
struct Node* dequeue() {
    if (front == NULL) return NULL; 
    struct Node* tNode = front->tNode;
    struct QNode* temp = front;
    front = front->next;
    if (front == NULL) rear = NULL; 
    free(temp);
    return tNode;
}
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);
    levelOrderTraversal(root);
    return 0;
}
Java
import java.util.LinkedList;
import java.util.Queue;

class Node {
    int data;
    Node left, right;
    Node(int data) {
        this.data = data;
        left = right = null;
    }
}

public class GfG {
    static void levelOrderTraversal(Node root) {
        if (root == null) return;

        Queue<Node> q = new LinkedList<>();
        q.add(root);

        while (!q.isEmpty()) {
            Node curr = q.poll();
            System.out.print(curr.data + " ");

            if (curr.left != null) q.add(curr.left);
            if (curr.right != null) q.add(curr.right);
        }
    }

    public static void main(String[] args) {
        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);
        levelOrderTraversal(root);
    }
}
Python
from collections import deque

# Define a tree node structure
class TreeNode:
    def __init__(self, x):
        self.value = x
        self.left = None
        self.right = None

# Function to perform level order traversal
def level_order_traversal(root):
    if not root:
        return

    queue = deque([root])

    while queue:
        node = queue.popleft()
        print(node.value, end=" ")

        if node.left:
            queue.append(node.left)
        if node.right:
            queue.append(node.right)

# Example usage
if __name__ == "__main__":
    root = TreeNode(1)
    root.left = TreeNode(2)
    root.right = TreeNode(3)
    root.left.left = TreeNode(4)
    root.left.right = TreeNode(5)
    root.right.right = TreeNode(6)

    print("Level Order Traversal: ", end="")
    level_order_traversal(root)
C#
using System;
using System.Collections.Generic;

// Define a tree node structure
public class TreeNode {
    public int Value;
    public TreeNode Left;
    public TreeNode Right;
    public TreeNode(int x) { Value = x; }
}

// Function to perform level order traversal
public class LevelOrderTraversal {
    public static void LevelOrder(TreeNode root) {
        if (root == null) return;

        Queue<TreeNode> queue = new Queue<TreeNode>();
        queue.Enqueue(root);

        while (queue.Count > 0) {
            TreeNode node = queue.Dequeue();
            Console.Write(node.Value + " ");

            if (node.Left != null) queue.Enqueue(node.Left);
            if (node.Right != null) queue.Enqueue(node.Right);
        }
    }

    public static void Main() {
        // Example usage
        TreeNode root = new TreeNode(1);
        root.Left = new TreeNode(2);
        root.Right = new TreeNode(3);
        root.Left.Left = new TreeNode(4);
        root.Left.Right = new TreeNode(5);
        root.Right.Right = new TreeNode(6);

        Console.Write("Level Order Traversal: ");
        LevelOrder(root);
    }
}
JavaScript
class TreeNode {
    constructor(value) {
        this.value = value;
        this.left = null;
        this.right = null;
    }
}

// Function to perform level order traversal
function levelOrderTraversal(root) {
    if (!root) return;

    let queue = [];
    queue.push(root);

    while (queue.length > 0) {
        let node = queue.shift();
        console.log(node.value + " ");

        if (node.left) queue.push(node.left);
        if (node.right) queue.push(node.right);
    }
}

// Example usage
let root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(6);

console.log("Level Order Traversal: ");
levelOrderTraversal(root);

Output
1 2 3 4 5 6 

Other Tree Traversals:

  1. Boundary Traversal
  2. Diagonal Traversal

1. Boundary Traversal:

Boundary Traversal of a Tree includes:

  • left boundary (nodes on left excluding leaf nodes)
  • leaves (consist of only the leaf nodes)
  • right boundary (nodes on right excluding leaf nodes)

Algorithm for Boundary Traversal:

BoundaryTraversal(tree)

  • If root is not null:
    • Print root’s data
    • PrintLeftBoundary(root->left) // Print the left boundary nodes
    • PrintLeafNodes(root->left) // Print the leaf nodes of left subtree
    • PrintLeafNodes(root->right) // Print the leaf nodes of right subtree
    • PrintRightBoundary(root->right) // Print the right boundary nodes

Uses of Boundary Traversal:

  • Boundary traversal helps visualize the outer structure of a binary tree, providing insights into its shape and boundaries.
  • Boundary traversal provides a way to access and modify these nodes, enabling operations such as pruning or repositioning of boundary nodes.

2. Diagonal Traversal

In the Diagonal Traversal of a Tree, all the nodes in a single diagonal will be printed one by one.

Algorithm for Diagonal Traversal:

DiagonalTraversal(tree):

  • If root is not null:
    • Create an empty map
    • DiagonalTraversalUtil(root, 0, M) // Call helper function with initial diagonal level 0
    • For each key-value pair (diagonalLevel, nodes) in M:
      • For each node in nodes:
      • Print node’s data

DiagonalTraversalUtil(node, diagonalLevel, M):

  • If node is null:
  • Return
  • If diagonalLevel is not present in M:
    • Create a new list in M for diagonalLevel
  • Append node’s data to the list at M[diagonalLevel]
  • DiagonalTraversalUtil(node->left, diagonalLevel + 1, M) // Traverse left child with increased diagonal level
  • DiagonalTraversalUtil(node->right, diagonalLevel, M) // Traverse right child with same diagonal level

Uses of Diagonal Traversal:

  • Diagonal traversal helps in visualizing the hierarchical structure of binary trees, particularly in tree-based data structures like binary search trees (BSTs) and heap trees.
  • Diagonal traversal can be utilized to calculate path sums along diagonals in a binary tree.

Frequently Asked Questions (FAQs) on Tree Traversal Techniques:

1. What are tree traversal techniques?

Tree traversal techniques are methods used to visit and process all nodes in a tree data structure. They allow you to access each node exactly once in a systematic manner.

2. What are the common types of tree traversal?

The common types of tree traversal are: Inorder traversal, Preorder traversal, Postorder traversal, Level order traversal (Breadth-First Search)

3. What is Inorder traversal?

Inorder traversal is a depth-first traversal method where nodes are visited in the order: left subtree, current node, right subtree.

4. What is preorder traversal?

Preorder traversal is a depth-first traversal method where nodes are visited in the order: current node, left subtree, right subtree.

5. What is postorder traversal?

Postorder traversal is a depth-first traversal method where nodes are visited in the order: left subtree, right subtree, current node.

6. What is level order traversal?

Level order traversal, also known as Breadth-First Search (BFS), visits nodes level by level, starting from the root and moving to the next level before traversing deeper.

7. When should I use each traversal technique?

Inorder traversal is often used for binary search trees to get nodes in sorted order.

Preorder traversal is useful for creating a copy of the tree.

Postorder traversal is commonly used in expression trees to evaluate expressions.

Level order traversal is helpful for finding the shortest path between nodes.

8. How do I implement tree traversal algorithms?

Tree traversal algorithms can be implemented recursively or iteratively, depending on the specific requirements and programming language being used.

9. Can tree traversal algorithms be applied to other tree-like structures?

Yes, tree traversal algorithms can be adapted to traverse other tree-like structures such as binary heaps, n-ary trees, and graphs represented as trees.

10. Are there any performance considerations when choosing a traversal technique?

Performance considerations depend on factors such as the size and shape of the tree, available memory, and specific operations being performed during traversal. In general, the choice of traversal technique may affect the efficiency of certain operations, so it’s important to choose the most suitable method for your specific use case.

Some other important Tutorials:



Previous Article
Next Article

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
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
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
Cartesian tree from inorder traversal | Segment Tree
Given an in-order traversal of a cartesian tree, the task is to build the entire tree from it. Examples: Input: arr[] = {1, 5, 3} Output: 1 5 3 5 / \ 1 3 Input: arr[] = {3, 7, 4, 8} Output: 3 7 4 8 8 / 7 / \ 3 4 Approach: We have already seen an algorithm here that takes O(NlogN) time on an average but can get to O(N2) in the worst case.In this art
13 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
Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
Given the level order traversal of a Complete Binary Tree, determine whether the Binary Tree is a valid Min-Heap Examples: Input : level = [10, 15, 14, 25, 30] Output : True The tree of the given level order traversal is 10 / \ 15 14 / \ 25 30 We see that each parent has a value less than its child, and hence satisfies the min-heap property Input :
6 min read
If you are given two traversal sequences, can you construct the binary tree?
It depends on what traversals are given. If one of the traversal methods is Inorder then the tree can be constructed, otherwise not. Therefore, following combination can uniquely identify a tree. Inorder and Preorder. Inorder and Postorder. Inorder and Level-order. And following do not. Postorder and Preorder. Preorder and Level-order. Postorder an
1 min read
Inorder Tree Traversal without recursion and without stack!
Using Morris Traversal, we can traverse the tree without using stack and recursion. The idea of Morris Traversal is based on Threaded Binary Tree. In this traversal, we first create links to Inorder successor and print the data using these links, and finally revert the changes to restore original tree. 1. Initialize current as root 2. While current
9 min read
Construct Special Binary Tree from given Inorder traversal
Given Inorder Traversal of a Special Binary Tree in which the key of every node is greater than keys in left and right children, construct the Binary Tree and return root. Examples: Input: inorder[] = {5, 10, 40, 30, 28} Output: root of following tree 40 / \ 10 30 / \ 5 28 Input: inorder[] = {1, 5, 10, 40, 30, 15, 28, 20} Output: root of following
14 min read
Perfect Binary Tree Specific Level Order Traversal
Given a Perfect Binary Tree like below: Print the level order of nodes in following specific manner: 1 2 3 4 7 5 6 8 15 9 14 10 13 11 12 16 31 17 30 18 29 19 28 20 27 21 26 22 25 23 24i.e. print nodes in level order but nodes should be from left and right side alternatively. Here 1st and 2nd levels are trivial. While 3rd level: 4(left), 7(right), 5
15+ min read
Postorder traversal of Binary Tree without recursion and without stack
Given a binary tree, perform postorder traversal. Prerequisite - Inorder/preorder/postorder traversal of tree We have discussed the below methods for postorder traversal. 1) Recursive Postorder Traversal. 2) Postorder traversal using Stack. 2) Postorder traversal using two Stacks. Approach 1 The approach used is based on using an unordered set to k
15 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
Build Binary Tree from BST such that it's level order traversal prints sorted data
Construct a Binary Tree from the given Binary Search Tree such that it's level order traversal outputs sorted data.Examples: Input: Output: 1 2 3 Input: Output: 1 2 3 4 5 Approach: Perform the inorder traversal of the given Binary Search Tree.Add each node in level order to the Binary Tree.Finally, print the level order traversal of the created Bin
12 min read
Reverse Morris traversal using Threaded Binary Tree
What is Morris traversal?Morris (InOrder) Traversal is a tree traversal algorithm that does not use recursion or stacks. This traversal creates links as descendants and outputs nodes using those links. Finally, undo the changes to restore the original tree.Given a binary tree, task is to do reverse inorder traversal using Morris Traversal. Prerequi
10 min read
Traversal of tree with k jumps allowed between nodes of same height
There is a tree with N nodes and node 1 is the root node. Each node of the tree can contain fruit or not. Initially, you are at the root node and start climbing on the tree. You can jump from a node to any node at the same level(i.e. the height of nodes from the root are same), During climbing from root node you can only make maximum K jumps. (K
12 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
Find n-th node in Postorder traversal of a Binary Tree
Given a Binary tree and a number N, write a program to find the N-th node in the Postorder traversal of the given Binary tree. Prerequisite: Tree Traversal Examples: Input : N = 4 11 / \ 21 31 / \ 41 51 Output : 31 Explanation: Postorder Traversal of given Binary Tree is 41 51 21 31 11, so 4th node will be 31. Input : N = 5 25 / \ 20 30 / \ / \ 18
13 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
Reverse zigzag Traversal of a Binary Tree
Given a Binary Tree, the task is to print the Reverse zigzag Order of the tree.Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 Output: 6 5 4 2 3 1 Input: 5 / \ 9 3 / \ 6 4 / \ 8 7 Output: 7 8 6 4 3 9 5 Approach: The idea is to traverse the tree in a Reverse Level Order manner but with a slight modification. We will use a variable flag and initially set it's
10 min read
Anti Clockwise spiral traversal of a binary tree
Given a binary tree, the task is to print the nodes of the tree in an anti-clockwise spiral manner. Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 Output: 1 4 5 6 7 3 2 Input: 1 / \ 2 3 / / \ 4 5 6 / \ / / \ 7 8 9 10 11 Output: 1 7 8 9 10 11 3 2 4 5 6 Approach: The idea is to use two variables i initialized to 1 and j initialized to the height of tree
15+ min read
Reverse Clockwise spiral traversal of a binary tree
Given a Binary Tree. The task is to print the circular reverse clockwise spiral order traversal of the given binary tree.Reverse Clockwise Traversal means to traverse the tree in clockwise direction spirally starting from the bottom instead of top root node.Examples: Input : 1 / \ 2 3 / \ \ 4 5 6 / / \ 7 8 9 Output : 9 8 7 1 6 5 4 2 3 Input : 20 /
11 min read
Kth node in Diagonal Traversal of Binary Tree
Given a binary tree and a value K. The task is to print the k-th node in the diagonal traversal of the binary tree. If no such node exists then print -1.Examples: Input : 8 / \ 3 10 / / \ 1 6 14 / \ / 4 7 13 k = 5 Output : 6 Diagonal Traversal of the above tree is: 8 10 14 3 6 7 13 1 4 Input : 1 / \ 2 3 / \ 4 5 k = 7 Output : -1 Approach: The idea
9 min read
Find the Kth node in the DFS traversal of a given subtree in a Tree
Given a tree with N nodes, and two integers K and V. The task is to find the Kth node in the DFS traversal of the vertex V.Consider the below Tree: DFS of node number 1 is [1, 2, 3, 5, 6, 8, 7, 9, 4]. DFS of node number 3 is [3, 5, 6, 8, 7, 9] DFS of node number 7 is [7, 9] DFS of node number 9 is [9]. Print "-1" if the numbers in the DFS of vertex
10 min read
Find the kth node in vertical order traversal of a Binary Tree
Given a binary tree and an integer k, the task is to print the kth node in the vertical order traversal of binary tree.If no such node exists then print -1.The vertical order traversal of a binary tree means to print it vertically.Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 \ \ 8 9 k = 3 Output: 1 The vertical order traversal of above tree is: 4 2 1
9 min read
Density of Binary Tree using Level Order Traversal
Given a Binary Tree, find the density of it by doing one traversal of it.The density of binary tree is defined as: Density of Binary Tree = Size / Height Examples: Input : Root of following tree 10 / \ 20 30 Output : 1.5 Height of given tree = 2 Size of given tree = 3 Input : Root of the following tree 10 / 20 / 30 Output : 1 Height of given tree =
7 min read
Construct the Rooted tree by using start and finish time of its DFS traversal
Given start and finish times of DFS traversal of N vertices that are available in a Rooted tree, the task is to construct the tree (Print the Parent of each node). Parent of the root node is 0.Examples: Input: Start[] = {2, 4, 1, 0, 3}, End[] = {3, 5, 4, 5, 4} Output: 3 4 4 0 3 Given Tree is -: 4(0, 5) / \ (1, 4)3 2(4, 5) / \ (2, 3)1 5(3, 4) The ro
8 min read
Construct a Complete N-ary Tree from given Postorder Traversal
Given an array arr[] of size M that contains the post-order traversal of a complete N-ary tree, the task is to generate the N-ary tree and print its preorder traversal. A complete tree is a tree where all the levels of the tree are completely filled, except may be for the last level but the nodes in the last level are as left as possible. Examples:
13 min read
Flatten Binary Tree in order of Level Order Traversal
Given a Binary Tree, the task is to flatten it in order of Level order traversal of the tree. In the flattened binary tree, the left node of all the nodes must be NULL.Examples: Input: 1 / \ 5 2 / \ / \ 6 4 9 3 Output: 1 5 2 6 4 9 3 Input: 1 \ 2 \ 3 \ 4 \ 5 Output: 1 2 3 4 5 Approach: We will solve this problem by simulating the Level order travers
7 min read
Flatten binary tree in order of post-order traversal
Given a binary tree, the task is to flatten it in order of its post-order traversal. In the flattened binary tree, the left node of all the nodes must be NULL. Examples: Input: 5 / \ 3 7 / \ / \ 2 4 6 8 Output: 2 4 3 6 8 7 5 Input: 1 \ 2 \ 3 \ 4 \ 5 Output: 5 4 3 2 1 A simple approach will be to recreate the Binary Tree from its post-order traversa
7 min read