The Wayback Machine - https://web.archive.org/web/20240624015942/https://www.geeksforgeeks.org/iterative-diagonal-traversal-binary-tree/
Open In App

Iterative diagonal traversal of binary tree

Last Updated : 31 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Consider lines of slope -1 passing between nodes. Given a Binary Tree, print all diagonal elements in a binary tree belonging to the same line.

Input : Root of below tree

Output : 
Diagonal Traversal of binary tree : 
 8 10 14
 3 6 7 13
 1 4

We have discussed the recursive solution in the below post.
Diagonal Traversal of Binary Tree
In this post, an iterative solution is discussed. The idea is to use a queue to store only the left child of the current node. After printing the data of the current node make the current node to its right child if present. 
A delimiter NULL is used to mark the starting of the next diagonal.

Below is the implementation of the above approach.  

C++




/* C++ program to construct string from binary tree*/
#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree node has data, pointer to left
   child and a pointer to right child */
struct Node {
    int data;
    Node *left, *right;
};
 
/* Helper function that allocates a new node */
Node* newNode(int data)
{
    Node* node = (Node*)malloc(sizeof(Node));
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
 
// Iterative function to print diagonal view
void diagonalPrint(Node* root)
{
    // base case
    if (root == NULL)
        return;
 
    // inbuilt queue of Treenode
    queue<Node*> q;
 
    // push root
    q.push(root);
 
    // push delimiter
    q.push(NULL);
 
    while (!q.empty()) {
        Node* temp = q.front();
        q.pop();
 
        // if current is delimiter then insert another
        // for next diagonal and cout nextline
        if (temp == NULL) {
 
            // if queue is empty return
            if (q.empty())
                return;
 
            // output nextline
            cout << endl;
 
            // push delimiter again
            q.push(NULL);
        }
        else {
            while (temp) {
                cout << temp->data << " ";
 
                // if left child is present
                // push into queue
                if (temp->left)
                    q.push(temp->left);
 
                // current equals to right child
                temp = temp->right;
            }
        }
    }
}
 
// Driver Code
int main()
{
    Node* root = newNode(8);
    root->left = newNode(3);
    root->right = newNode(10);
    root->left->left = newNode(1);
    root->left->right = newNode(6);
    root->right->right = newNode(14);
    root->right->right->left = newNode(13);
    root->left->right->left = newNode(4);
    root->left->right->right = newNode(7);
    diagonalPrint(root);
}


Java




// Java program to con string from binary tree
import java.util.*;
public class solution
{
 
   
// A binary tree node has data, pointer to left
 //  child and a pointer to right child
static class Node {
    int data;
    Node left, right;
};
   
// Helper function that allocates a new node
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = node.right = null;
    return (node);
}
   
// Iterative function to print diagonal view
static void diagonalPrint(Node root)
{
    // base case
    if (root == null)
        return;
   
    // inbuilt queue of Treenode
    Queue<Node> q= new LinkedList<Node>();
   
    // add root
    q.add(root);
   
    // add delimiter
    q.add(null);
   
    while (q.size()>0) {
        Node temp = q.peek();
        q.remove();
   
        // if current is delimiter then insert another
        // for next diagonal and cout nextline
        if (temp == null) {
   
            // if queue is empty return
            if (q.size()==0)
                return;
   
            // output nextline
            System.out.println();
   
            // add delimiter again
            q.add(null);
        }
        else {
            while (temp!=null) {
                System.out.print( temp.data + " ");
   
                // if left child is present 
                // add into queue
                if (temp.left!=null)
                    q.add(temp.left);
   
                // current equals to right child
                temp = temp.right;
            }
        }
    }
}
   
// Driver Code
public static void main(String args[])
{
    Node root = newNode(8);
    root.left = newNode(3);
    root.right = newNode(10);
    root.left.left = newNode(1);
    root.left.right = newNode(6);
    root.right.right = newNode(14);
    root.right.right.left = newNode(13);
    root.left.right.left = newNode(4);
    root.left.right.right = newNode(7);
    diagonalPrint(root);
}
}
//contributed by Arnab Kundu


Python3




# Python3 program to construct string from binary tree
class Node:
    def __init__(self,data):
        self.val = data
        self.left = None
        self.right = None
         
# Function to print diagonal view
def diagonalprint(root):
     
    # base case
    if root is None:
        return
         
    # queue of treenode
    q = []
     
    # Append root
    q.append(root)
     
    # Append delimiter
    q.append(None)
 
    while len(q) > 0:
        temp = q.pop(0)
         
        # If current is delimiter then insert another
        # for next diagonal and cout nextline
        if not temp:
             
            # If queue is empty then return
            if len(q) == 0:
                return
                 
            # Print output on nextline
            print(' ')
             
            # append delimiter again
            q.append(None)
 
        else:
            while temp:
                print(temp.val, end = ' ')
                 
                # If left child is present
                # append into queue
                if temp.left:
                    q.append(temp.left)
                     
                # current equals to right child
                temp = temp.right
 
# Driver Code
root = Node(8)
root.left = Node(3)
root.right = Node(10)
root.left.left = Node(1)
root.left.right = Node(6)
root.right.right = Node(14)
root.right.right.left = Node(13)
root.left.right.left = Node(4)
root.left.right.right = Node(7)
diagonalprint(root)
 
# This code is contributed by Praveen kumar


C#




// C# program to con string from binary tree
using System;
using System.Collections;
 
class GFG
{
 
// A binary tree node has data,
// pointer to left child and
// a pointer to right child
public class Node
{
    public int data;
    public Node left, right;
};
     
// Helper function that
// allocates a new node
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = node.right = null;
    return (node);
}
     
// Iterative function to print diagonal view
static void diagonalPrint(Node root)
{
    // base case
    if (root == null)
        return;
     
    // inbuilt queue of Treenode
    Queue q = new Queue();
     
    // Enqueue root
    q.Enqueue(root);
     
    // Enqueue delimiter
    q.Enqueue(null);
     
    while (q.Count > 0)
    {
        Node temp = (Node) q.Peek();
        q.Dequeue();
     
        // if current is delimiter then insert another
        // for next diagonal and cout nextline
        if (temp == null)
        {
     
            // if queue is empty return
            if (q.Count == 0)
                return;
     
            // output nextline
            Console.WriteLine();
     
            // Enqueue delimiter again
            q.Enqueue(null);
        }
        else
        {
            while (temp != null)
            {
                Console.Write( temp.data + " ");
     
                // if left child is present
                // Enqueue into queue
                if (temp.left != null)
                    q.Enqueue(temp.left);
     
                // current equals to right child
                temp = temp.right;
            }
        }
    }
}
     
// Driver Code
public static void Main(String []args)
{
    Node root = newNode(8);
    root.left = newNode(3);
    root.right = newNode(10);
    root.left.left = newNode(1);
    root.left.right = newNode(6);
    root.right.right = newNode(14);
    root.right.right.left = newNode(13);
    root.left.right.left = newNode(4);
    root.left.right.right = newNode(7);
    diagonalPrint(root);
}
}
 
// This code is contributed by Arnab Kundu


Javascript




<script>
 
    // JavaScript program to con string from binary tree
     
    class Node
    {
        constructor(data) {
           this.left = null;
           this.right = null;
           this.data = data;
        }
    }
 
    // Helper function that allocates a new node
    function newNode(data)
    {
        let node = new Node(data);
        return (node);
    }
 
    // Iterative function to print diagonal view
    function diagonalPrint(root)
    {
        // base case
        if (root == null)
            return;
 
        // inbuilt queue of Treenode
        let q= [];
 
        // add root
        q.push(root);
 
        // add delimiter
        q.push(null);
 
        while (q.length>0) {
            let temp = q[0];
            q.shift();
 
            // if current is delimiter then insert another
            // for next diagonal and cout nextline
            if (temp == null) {
 
                // if queue is empty return
                if (q.length==0)
                    return;
 
                // output nextline
                document.write("</br>");
 
                // add delimiter again
                q.push(null);
            }
            else {
                while (temp!=null) {
                    document.write( temp.data + " ");
 
                    // if left child is present
                    // add into queue
                    if (temp.left!=null)
                        q.push(temp.left);
 
                    // current equals to right child
                    temp = temp.right;
                }
            }
        }
    }
     
    let root = newNode(8);
    root.left = newNode(3);
    root.right = newNode(10);
    root.left.left = newNode(1);
    root.left.right = newNode(6);
    root.right.right = newNode(14);
    root.right.right.left = newNode(13);
    root.left.right.left = newNode(4);
    root.left.right.right = newNode(7);
    diagonalPrint(root);
 
</script>


Output

8 10 14 
3 6 7 13 
1 4 

Time Complexity: O(n), where n is the total number of nodes in the binary tree.
Auxiliary Space: O(n),  As we use a queue to store the nodes, the space complexity is also O(n).

Method: Without using a delimiter

Just like level order traversal, use a queue. Little modification is to be done. 

if(curr.left != null) -> add it to the queue
and move curr pointer to right of curr.

if curr = null, then remove a node from queue.

Implementation:

C++




/* C++ program to print the diagonal traversal of binary
 * tree*/
#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree node has data, pointer to left
   child and a pointer to right child */
struct Node {
    int data;
    Node *left, *right;
};
 
/* Helper function that allocates a new node */
Node* newNode(int data)
{
    Node* node = (Node*)malloc(sizeof(Node));
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
// root node
Node* root;
 
// function to print in diagonal order
void traverse()
{
    // if the tree is empty, do not have to print
    // anything
    if (root == NULL)
        return;
 
    // if root is not empty, point curr node to the
    // root node
    Node* curr = root;
 
    // Maintain a queue to store left child
    queue<Node*> q;
 
    // continue till the queue is empty and curr is null
    while (!q.empty() || curr != NULL) {
        // if curr is not null
        // 1. print the data of the curr node
        // 2. if left child is present, add it to the queue
        // 3. Move curr pointer to the right
        if (curr != NULL) {
            cout << curr->data << " ";
 
            if (curr->left != NULL)
                q.push(curr->left);
            curr = curr->right;
        }
        // if curr is null, remove a node from the queue
        // and point it to curr node
        else {
            curr = q.front();
            q.pop();
        }
    }
}
 
// Driver Code
int main()
{
    root = newNode(8);
    root->left = newNode(3);
    root->right = newNode(10);
    root->left->left = newNode(1);
    root->left->right = newNode(6);
    root->right->right = newNode(14);
    root->right->right->left = newNode(13);
    root->left->right->left = newNode(4);
    root->left->right->right = newNode(7);
    traverse();
}
 
// This code is contributed by Abhijeet Kumar(abhijeet19403)


Java




import java.util.Queue;
import java.util.LinkedList;
 
//Node
class Node{
    int data;
    Node left;
    Node right;
     
    //Constructor for initializing the value of the node along with
    //left and right pointers
    Node(int data){
        this.data = data;
        left = right = null;
    }
}
 
public class DiagonalTraversal {
    //root node
    Node root = null;
     
    //function to print in diagonal order
    void traverse() {
        //if the tree is empty, do not have to print
        //anything
        if(root == null)
            return;
         
        //if root is not empty, point curr node to the
        //root node
        Node curr = root;
         
        //Maintain a queue to store left child
        Queue<Node> q = new LinkedList<>();
         
        //continue till the queue is empty and curr is null
        while(!q.isEmpty()  ||  curr!=null) {
            //if curr is null
            //1. print the data of the curr node
            //2. if left child is present, add it to the queue
            //3. Move curr pointer to the right
            if(curr != null) {
                System.out.print(curr.data+" ");
                 
                if(curr.left != null)
                    q.add(curr.left);
                curr = curr.right;
            }
            //if curr is null, remove a node from the queue
            //and point it to curr node
            else {
                curr = q.remove();
            }
        }
    }
     
    //Driver function
    public static void main(String args[]) {
        DiagonalTraversal tree = new DiagonalTraversal();
/*                 8
               /  \
              3    10
             / \    \
            1   6     14
               / \    /
              4   7  13            */
         
        //construction of the tree
        tree.root = new Node(8);
        tree.root.left = new Node(3);
        tree.root.right = new Node(10);
        tree.root.left.left = new Node(1);
        tree.root.left.right = new Node(6);
        tree.root.right.right = new Node(14);
        tree.root.right.right.left = new Node(13);
        tree.root.left.right.left = new Node(4);
        tree.root.left.right.right = new Node(7);
         
        //function call
        tree.traverse();
    }
}
 
//This method is contributed by Likhita AVL


Python3




# Python3 program to print the diagonal traversal of binary tree
 
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
#root node
root=Node(0)
 
# function to print in diagonal order
def traverse():
    # if the tree is empty, do not have to print
    # anything
    if root is None:
        return
 
    # if root is not empty, point curr node to the
    # root node
    curr = root
 
    # Maintain a queue to store left child
    q = []
 
    # continue till the queue is empty and curr is null
    while(len(q)!=0 or  curr != None):
            # if curr is not null
            # 1. print the data of the curr node
            # 2. if left child is present, add it to the queue
            # 3. Move curr pointer to the right
        if(curr != None):
            print(curr.data,end=" ")
 
            if(curr.left != None):
                q.append(curr.left)
            curr = curr.right
            # if curr is null, remove a node from the queue
            # and point it to curr node
        else:
            curr = q.pop(0)
 
 
# Driver Code
root = Node(8)
root.left = Node(3)
root.right = Node(10)
root.left.left = Node(1)
root.left.right = Node(6)
root.right.right = Node(14)
root.right.right.left = Node(13)
root.left.right.left = Node(4)
root.left.right.right = Node(7)
traverse()
 
# This code is contributed by Abhijeet Kumar(abhijeet19403)


C#




using System;
using System.Collections.Generic;
 
// Node
public class Node
{
    public int data;
    public Node left;
    public Node right;
      
    // Constructor for initializing the value
    // of the node along with left and right pointers
    public Node(int data)
    {
        this.data = data;
        left = right = null;
    }
}
 
public class DiagonalTraversal{
 
// Root node
Node root = null;
  
// Function to print in diagonal order
void traverse()
{
     
    // If the tree is empty, do not have to print
    // anything
    if (root == null)
        return;
      
    // If root is not empty, point curr node to the
    // root node
    Node curr = root;
      
    // Maintain a queue to store left child
    Queue<Node> q = new Queue<Node>();
      
    // Continue till the queue is empty
    // and curr is null
    while (q.Count != 0 || curr != null)
    {
         
        // If curr is null
        // 1. print the data of the curr node
        // 2. if left child is present, add it to the queue
        // 3. Move curr pointer to the right
        if (curr != null)
        {
            Console.Write(curr.data + " ");
              
            if (curr.left != null)
                q.Enqueue(curr.left);
                 
            curr = curr.right;
        }
         
        // If curr is null, remove a node from
        // the queue and point it to curr node
        else
        {
            curr = q.Dequeue();
        }
    }
}
 
// Driver code
static public void Main()
{
     
    DiagonalTraversal tree = new DiagonalTraversal();
    /*       8
           /  \
          3    10
         / \    \
        1   6     14
           / \    /
          4   7  13            */
      
    // Construction of the tree
    tree.root = new Node(8);
    tree.root.left = new Node(3);
    tree.root.right = new Node(10);
    tree.root.left.left = new Node(1);
    tree.root.left.right = new Node(6);
    tree.root.right.right = new Node(14);
    tree.root.right.right.left = new Node(13);
    tree.root.left.right.left = new Node(4);
    tree.root.left.right.right = new Node(7);
      
    // Function call
    tree.traverse();
}
}
 
// This code is contributed by rag2127


Javascript




<script>
 
//Node
class Node
{
    // Constructor for initializing the value of the node along with
    // left and right pointers
    constructor(data)
    {
        this.data = data;
        this.left = this.right = null;
    }
}
 
// root node
let root = null;
 
// function to print in diagonal order
function traverse()
{
    // if the tree is empty, do not have to print
        // anything
        if(root == null)
            return;
          
        // if root is not empty, point curr node to the
        // root node
        let curr = root;
          
        // Maintain a queue to store left child
        let q = [];
          
        // continue till the queue is empty and curr is null
        while(q.length!=0  ||  curr!=null) {
            // if curr is null
            // 1. print the data of the curr node
            // 2. if left child is present, add it to the queue
            // 3. Move curr pointer to the right
            if(curr != null) {
                document.write(curr.data+" ");
                  
                if(curr.left != null)
                    q.push(curr.left);
                curr = curr.right;
            }
            // if curr is null, remove a node from the queue
            // and point it to curr node
            else {
                curr = q.shift();
            }
       }
}
 
// Driver function
 
/*               8
               /  \
              3    10
             / \    \
            1   6     14
               / \    /
              4   7  13            */
 
//construction of the tree
root = new Node(8);
root.left = new Node(3);
root.right = new Node(10);
root.left.left = new Node(1);
root.left.right = new Node(6);
root.right.right = new Node(14);
root.right.right.left = new Node(13);
root.left.right.left = new Node(4);
root.left.right.right = new Node(7);
 
// function call
traverse();
 
 
// This code is contributed by avanitrachhadiya2155
 
</script>


Output

8 10 14 3 6 7 13 1 4 

Time Complexity: O(n), As we are traversing every element only once.
Auxiliary Space: O(n), Extra space is used to store the elements in the queue.



Similar Reads

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
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
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
Diagonal Traversal of Binary Tree
Consider lines with a slope of -1 that cross through nodes. Print all diagonal elements in a binary tree that belong to the same line, given a binary tree. Input : Root of below tree Output : Diagonal Traversal of binary tree: 8 10 14 3 6 7 13 1 4Observation : root and root-&gt;right values will be prioritized over all root-&gt;left values.Recommen
15+ min read
Iterative Boundary Traversal of Complete Binary tree
Given a complete binary tree, traverse it such that all the boundary nodes are visited in Anti-Clockwise order starting from the root. Example: Input: 18 / \ 15 30 / \ / \ 40 50 100 20 Output: 18 15 40 50 100 20 30 Approach: Traverse left-most nodes of the tree from top to down. (Left boundary)Traverse bottom-most level of the tree from left to rig
9 min read
Check whether a binary tree is a full binary tree or not | Iterative Approach
Given a binary tree containing n nodes. The problem is to check whether the given binary tree is a full binary tree or not. A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has only one child node. Examples: Input : 1 / \ 2 3 / \ 4 5 Outp
8 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
Iterative Postorder Traversal of N-ary Tree
Given an N-ary tree, the task is to find the post-order traversal of the given tree iteratively.Examples: Input: 1 / | \ 3 2 4 / \ 5 6 Output: [5, 6, 3, 2, 4, 1] Input: 1 / \ 2 3 Output: [2, 3, 1] Approach:We have already discussed iterative post-order traversal of binary tree using one stack. We will extend that approach for the n-ary tree. The id
10 min read
Filling diagonal to make the sum of every row, column and diagonal equal of 3x3 matrix
Given 9 elements in a 3 x 3 matrix where the value of diagonals is 0. We need to find the values in the diagonal to make the sum of every row, column, and diagonal equal. Examples: Input: 0 3 6 5 0 5 4 7 0 Output: 6 3 6 5 5 5 4 7 4 Explanation: Now the value of the sum of any row or column is 15 Input: 0 4 4 4 0 4 4 4 0 Output: 4 4 4 4 4 4 4 4 4 Ap
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg