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 4
Observation : root and root->right values will be prioritized over all root->left values.
The plan is to make use of a map. Different slope distances are used in the map as a key. The map’s value is a node vector (or dynamic array). To save values in the map, we traverse the tree. We print the contents of the map after it has been constructed.
Below is the implementation of the above idea.
C++
// C++ program for diagonal // traversal of Binary Tree #include <bits/stdc++.h> using namespace std; Â
// Tree node struct Node { Â Â Â Â int data; Â Â Â Â Node *left, *right; }; Â
/* root - root of the binary tree    d - distance of current line from rightmost         -topmost slope.    diagonalPrint - multimap to store Diagonal                    elements (Passed by Reference) */ void diagonalPrintUtil(Node* root, int d,                 map< int , vector< int >> &diagonalPrint) {     // Base case     if (!root)         return ; Â
    // Store all nodes of same     // line together as a vector     diagonalPrint[d].push_back(root->data); Â
    // Increase the vertical     // distance if left child     diagonalPrintUtil(root->left,                       d + 1, diagonalPrint); Â
    // Vertical distance remains     // same for right child     diagonalPrintUtil(root->right,                          d, diagonalPrint); } Â
// Print diagonal traversal // of given binary tree void diagonalPrint(Node* root) {          // create a map of vectors     // to store Diagonal elements     map< int , vector< int > > diagonalPrint;     diagonalPrintUtil(root, 0, diagonalPrint); Â
    cout << "Diagonal Traversal of binary tree : \n" ;     for ( auto it :diagonalPrint)     {         vector< int > v=it.second;         for ( auto it:v)           cout<<it<< " " ;         cout<<endl;     } } Â
// Utility method to create a new node Node* newNode( int data) { Â Â Â Â Node* node = new Node; Â Â Â Â node->data = data; Â Â Â Â node->left = node->right = NULL; Â Â Â Â return node; } Â
// Driver program 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); Â
    /* Node* root = newNode(1);         root->left = newNode(2);         root->right = newNode(3);         root->left->left = newNode(9);         root->left->right = newNode(6);         root->right->left = newNode(4);         root->right->right = newNode(5);         root->right->left->right = newNode(7);         root->right->left->left = newNode(12);         root->left->right->left = newNode(11);         root->left->left->right = newNode(10);*/ Â
    diagonalPrint(root); Â
    return 0; } |
Java
// Java program for diagonal // traversal of Binary Tree import java.util.TreeMap; import java.util.Map.Entry; import java.util.Vector; Â
public class DiagonalTraversalBTree {     // Tree node     static class Node     {         int data;         Node left;         Node right;                  //constructor         Node( int data)         {             this .data=data;             left = null ;             right = null ;         }     }          /* root - root of the binary tree        d - distance of current line from rightmost             -topmost slope.        diagonalPrint - HashMap to store Diagonal                        elements (Passed by Reference) */     static void diagonalPrintUtil(Node root, int d,           TreeMap<Integer,Vector<Integer>> diagonalPrint)     {                   // Base case         if (root == null )             return ;                  // get the list at the particular d value         Vector<Integer> k = diagonalPrint.get(d);                  // k is null then create a         // vector and store the data         if (k == null )         {             k = new Vector<>();             k.add(root.data);         }                  // k is not null then update the list         else         {             k.add(root.data);         }                  // Store all nodes of same line         // together as a vector         diagonalPrint.put(d,k);                  // Increase the vertical distance         // if left child         diagonalPrintUtil(root.left,                          d + 1 , diagonalPrint);                   // Vertical distance remains         // same for right child         diagonalPrintUtil(root.right,                           d, diagonalPrint);     }          // Print diagonal traversal     // of given binary tree     static void diagonalPrint(Node root)     {                  // create a map of vectors         // to store Diagonal elements         TreeMap<Integer,Vector<Integer>>              diagonalPrint = new TreeMap<>();         diagonalPrintUtil(root, 0 , diagonalPrint);                  System.out.println( "Diagonal Traversal of Binary Tree" );         for (Entry<Integer, Vector<Integer>> entry :                           diagonalPrint.entrySet())         {             System.out.println(entry.getValue());         }     }          // Driver program     public static void main(String[] args)     {                  Node 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 );                  diagonalPrint(root);     } } // This code is contributed by Sumit Ghosh |
Python3
# Python program for diagonal # traversal of Binary Tree Â
# A binary tree node class Node: Â
    # Constructor to create a     # new binary tree node     def __init__( self , data):         self .data = data         self .left = None         self .right = None Â
Â
""" root - root of the binary tree    d - distance of current line from rightmost         -topmost slope.    diagonalPrint - multimap to store Diagonal                    elements (Passed by Reference) """ def diagonalPrintUtil(root, d, diagonalPrintMap):          # Base Case     if root is None :         return Â
    # Store all nodes of same line     # together as a vector     try :         diagonalPrintMap[d].append(root.data)     except KeyError:         diagonalPrintMap[d] = [root.data] Â
    # Increase the vertical distance     # if left child     diagonalPrintUtil(root.left,                         d + 1 , diagonalPrintMap)          # Vertical distance remains     # same for right child     diagonalPrintUtil(root.right,                            d, diagonalPrintMap) Â
Â
Â
# Print diagonal traversal of given binary tree def diagonalPrint(root): Â
    # Create a dict to store diagonal elements     diagonalPrintMap = dict ()          # Find the diagonal traversal     diagonalPrintUtil(root, 0 , diagonalPrintMap) Â
    print ( "Diagonal Traversal of binary tree : " )     for i in diagonalPrintMap:         for j in diagonalPrintMap[i]:             print (j,end = " " )         print () Â
Â
# Driver Program 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 Nikhil Kumar Singh(nickzuck_007) |
C#
using System; using System.Collections.Generic; Â
class Node { Â Â Â Â public int data; Â Â Â Â public Node left; Â Â Â Â public Node right; Â
    public Node( int data)     {         this .data = data;         this .left = null ;         this .right = null ;     } } Â
class BinaryTree { Â Â Â Â public static void diagonalPrintUtil(Node root, int d, Dictionary< int , List< int >> diagonalPrint) Â Â Â Â { Â Â Â Â Â Â Â Â if (root == null ) return ; Â
        if (!diagonalPrint.ContainsKey(d))         {             diagonalPrint[d] = new List< int >();         } Â
        diagonalPrint[d].Add(root.data); Â
        diagonalPrintUtil(root.left, d + 1, diagonalPrint);         diagonalPrintUtil(root.right, d, diagonalPrint);     } Â
    public static void diagonalPrint(Node root)     {         Dictionary< int , List< int >> diagonalPrint = new Dictionary< int , List< int >>();         diagonalPrintUtil(root, 0, diagonalPrint); Â
        Console.WriteLine( "Diagonal Traversal of Binary Tree" );         foreach (KeyValuePair< int , List< int >> entry in diagonalPrint)         {             Console.WriteLine( string .Join( " " , entry.Value));         }     } Â
    public static void Main( string [] args)     {         Node 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); Â
        diagonalPrint(root);     } } |
Javascript
//Javascript program for diagonal //traversal of Binary Tree class Node { Â Â constructor(data) { Â Â Â Â this .data = data; Â Â Â Â this .left = null ; Â Â Â Â this .right = null ; Â Â } } Â
function diagonalPrintUtil(root, d, diagonalPrint = new Map()) { Â Â if (!root) return ; Â
  let k = diagonalPrint.get(d) || [];   k.push(root.data);   diagonalPrint.set(d, k); Â
  diagonalPrintUtil(root.left, d + 1, diagonalPrint);   diagonalPrintUtil(root.right, d, diagonalPrint); } Â
function diagonalPrint(root) { Â Â const diagonalPrint = new Map(); Â Â diagonalPrintUtil(root, 0, diagonalPrint); Â
  console.log( "Diagonal Traversal of Binary Tree" );   for (const [key, value] of diagonalPrint) {     console.log(value);   } } Â
const 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); Â
diagonalPrint(root); Â
// This code is contributed by shivamsharma215 |
Diagonal Traversal of binary tree : 8 10 14 3 6 7 13 1 4
Time complexity: O( N logN )
Auxiliary Space: O( N )
The identical problem may be solved with a queue and an iterative method.
C++14
#include <bits/stdc++.h> using namespace std; Â
// Tree node struct Node { Â Â Â Â int data; Â Â Â Â Node *left, *right; }; Â
vector< int > diagonal(Node* root) { Â Â Â Â vector< int > diagonalVals; Â Â Â Â if (!root) Â Â Â Â Â Â Â Â return diagonalVals; Â
    // The leftQueue will be a queue which will store all     // left pointers while traversing the tree, and will be     // utilized when at any point right pointer becomes NULL Â
    queue<Node*> leftQueue;     Node* node = root; Â
    while (node) { Â
        // Add current node to output         diagonalVals.push_back(node->data);         // If left child available, add it to queue         if (node->left)             leftQueue.push(node->left); Â
        // if right child, transfer the node to right         if (node->right)             node = node->right; Â
        else {             // If left child Queue is not empty, utilize it             // to traverse further             if (!leftQueue.empty()) {                 node = leftQueue.front();                 leftQueue.pop();             }             else {                 // All the right childs traversed and no                 // left child left                 node = NULL;             }         }     }     return diagonalVals; } Â
// Utility method to create a new node Node* newNode( int data) { Â Â Â Â Node* node = new Node; Â Â Â Â node->data = data; Â Â Â Â node->left = node->right = NULL; Â Â Â Â return node; } Â
// Driver program 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); Â
    /* Node* root = newNode(1);             root->left = newNode(2);             root->right = newNode(3);             root->left->left = newNode(9);             root->left->right = newNode(6);             root->right->left = newNode(4);             root->right->right = newNode(5);             root->right->left->right = newNode(7);             root->right->left->left = newNode(12);             root->left->right->left = newNode(11);             root->left->left->right = newNode(10);*/ Â
    vector< int > diagonalValues = diagonal(root);     for ( int i = 0; i < diagonalValues.size(); i++) {         cout << diagonalValues[i] << " " ;     }     cout << endl; Â
    return 0; } |
Java
// Java Code for above approach import java.util.*; Â
// Tree node class Node { Â Â Â Â int data; Â Â Â Â Node left, right; }; Â
class BinaryTree { Â
    public static List<Integer> diagonal(Node root)     {         List<Integer> diagonalVals = new ArrayList<>();         if (root == null )             return diagonalVals; Â
        // The leftQueue will be a queue which will store         // all left pointers while traversing the tree, and         // will be utilized when at any point right pointer         // becomes NULL Â
        Queue<Node> leftQueue = new LinkedList<>();         Node node = root; Â
        while (node != null ) { Â
            // Add current node to output             diagonalVals.add(node.data);             // If left child available, add it to queue             if (node.left != null )                 leftQueue.add(node.left); Â
            // if right child, transfer the node to right             if (node.right != null )                 node = node.right;             else {                 // If left child Queue is not empty, utilize                 // it to traverse further                 if (!leftQueue.isEmpty()) {                     node = leftQueue.peek();                     leftQueue.remove();                 }                 else {                     // All the right childs traversed and no                     // left child left                     node = null ;                 }             }         }         return diagonalVals;     } Â
    // Utility method to create a new node     public static Node newNode( int data)     {         Node node = new Node();         node.data = data;         node.left = node.right = null ;         return node;     } Â
    // Driver program     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 ); Â
        /* Node* root = newNode(1);         root->left = newNode(2);         root->right = newNode(3);         root->left->left = newNode(9);         root->left->right = newNode(6);         root->right->left = newNode(4);         root->right->right = newNode(5);         root->right->left->right = newNode(7);         root->right->left->left = newNode(12);         root->left->right->left = newNode(11);         root->left->left->right = newNode(10);*/ Â
        List<Integer> diagonalValues = diagonal(root);         for ( int i = 0 ; i < diagonalValues.size(); i++) {             System.out.print(diagonalValues.get(i) + " " );         }         System.out.println();     } } Â
// This code is contributed by Tapesh(tapeshdua420) |
Python3
from collections import deque Â
# A binary tree node Â
Â
class Node: Â
    # Constructor to create a     # new binary tree node     def __init__( self , data):         self .data = data         self .left = None         self .right = None Â
Â
def diagonal(root): Â Â Â Â out = [] Â Â Â Â node = root Â
    # queue to store left nodes     left_q = deque()     while node: Â
        # append data to output array         out.append(node.data) Â
        # if left available add it to the queue         if node.left:             left_q.appendleft(node.left) Â
        # if right is available change the node         if node.right:             node = node.right         else : Â
            # else pop the left_q             if len (left_q) > = 1 :                 node = left_q.pop()             else :                 node = None     return out Â
Â
# 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 ) Â
print (diagonal(root)) |
C#
// C# Code for above approach using System; using System.Collections.Generic; using System.Linq; Â
// Tree node class Node { Â Â Â Â public int data; Â Â Â Â public Node left, right; } Â
class GFG { Â
    public static List< int > Diagonal(Node root)     {         var diagonalVals = new List< int >();         if (root == null )             return diagonalVals; Â
        // The leftQueue will be a queue which will store         // all left pointers while traversing the tree, and         // will be utilized when at any point right pointer         // becomes NULL Â
        var leftQueue = new Queue<Node>();         Node node = root; Â
        while (node != null ) { Â
            // Add current node to output             diagonalVals.Add(node.data);             // If left child available, add it to queue             if (node.left != null )                 leftQueue.Enqueue(node.left); Â
            // if right child, transfer the node to right             if (node.right != null )                 node = node.right;             else {                 // If left child Queue is not empty, utilize                 // it to traverse further                 if (leftQueue.Count > 0) {                     node = leftQueue.Peek();                     leftQueue.Dequeue();                 }                 else {                     // All the right childs traversed and no                     // left child left                     node = null ;                 }             }         }         return diagonalVals;     } Â
    // Utility method to create a new node     public static Node NewNode( int data)     {         var node = new Node();         node.data = data;         node.left = node.right = null ;         return node;     } Â
    // Driver program     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);                // Node root = NewNode(1);         // root.left = NewNode(2);         // root.right = NewNode(3);         // root.left.left = NewNode(9);         // root.left.right = NewNode(6);         // root.right.left = NewNode(4);         // root.right.right = NewNode(5);         // root.right.left.right = NewNode(7);         // root.right.left.left = NewNode(12);         // root.left.right.left = NewNode(11);         // root.left.left.right = NewNode(10); Â
Â
        var diagonalValues = Diagonal(root);         for ( int i = 0; i < diagonalValues.Count; i++) {             Console.Write(diagonalValues[i] + " " );         }         Console.WriteLine();     } } |
Javascript
// JavaScript program for the above approach // Tree node class Node{ Â Â Â Â constructor(data){ Â Â Â Â Â Â Â Â this .data = data; Â Â Â Â Â Â Â Â this .left = null ; Â Â Â Â Â Â Â Â this .right = null ; Â Â Â Â } } Â
function diagonal(root){     let diagonalVals = [];     if (root == null ) return diagonalVals;          // The leftQueue will be a queue which will store all     // left pointers while traversing the tree, and will be     // utilized when at any point right pointer becomes NULL          let leftQueue = [];     let node = root;          while (node != null ){         // Add current node to output         diagonalVals.push(node.data);         // if left child available, add it to queue         if (node.left != null )             leftQueue.push(node.left);                  // If right child, transfer the node to right         if (node.right != null )             node = node.right;                  else {             // if left child queue is not empty, utilize it             // to traverse further             if (leftQueue.length > 0){                 node = leftQueue.shift();             }             else {                 // All the right childs traversed and so                 // left child left                 node = null ;             }         }     }     return diagonalVals; } Â
// Utility method to create a new node function newNode(data){ Â Â Â Â node = new Node(data); Â Â Â Â return node; } Â
// Driver program 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) Â
let diagonalValues = diagonal(root); for (let i = 0; i<diagonalValues.length; i++){ Â Â Â Â console.log(diagonalValues[i] + " " ); } Â
// This code is contributed by Yash Agarwal(yashagarwal2852002) |
[8, 10, 14, 3, 6, 7, 13, 1, 4]
Time complexity: O(N)
Auxiliary Space: O(N)
Approach 2: Using Queue:
Every node will contribute to the formation of the following diagonal. Only when the element’s left is available will we push it into the queue. We’ll process the node and then go to the right.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h> using namespace std; Â
struct Node { Â Â Â Â int data; Â Â Â Â Node *left, *right; }; Â
Node* newNode( int data) { Â Â Â Â Node* node = new Node; Â Â Â Â node->data = data; Â Â Â Â node->left = node->right = NULL; Â Â Â Â return node; } Â
vector<vector< int > > result; void diagonalPrint(Node* root) { Â Â Â Â if (root == NULL) Â Â Â Â Â Â Â Â return ; Â
    queue<Node*> q;     q.push(root); Â
    while (!q.empty()) {         int size = q.size();         vector< int > answer; Â
        while (size--) {             Node* temp = q.front();             q.pop(); Â
            // traversing each component;             while (temp) {                 answer.push_back(temp->data); Â
                if (temp->left)                     q.push(temp->left); Â
                temp = temp->right;             }         }         result.push_back(answer);     } } Â
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); Â
    for ( int i = 0; i < result.size(); i++) {         for ( int j = 0; j < result[i].size(); j++)             cout << result[i][j] << " " ;         cout << endl;     } Â
    return 0; } |
Java
// THIS CODE IS CONTRIBUTED BY KIRTI AGARAWL(KIRTIAGARWAL23121999) import java.util.*; Â
public class GFG {     // Tree node     static class Node {         int data;         Node left;         Node right;         Node( int data) {             this .data = data;             this .left = null ;             this .right = null ;         }     } Â
    static class TNode {         Node node;         int level;         public TNode(Node n, int l){             this .node = n;             this .level = l;         }     } Â
    public static void diagonalPrint(Node root){         if (root == null ) return ;                TreeMap<Integer, List<Integer> > map = new TreeMap<Integer, List<Integer> >(); Â
        Queue<TNode> q = new LinkedList<TNode>();         q.add( new TNode(root, 0 )); Â
        while (!q.isEmpty()) {             TNode curr = q.poll();             map.putIfAbsent(curr.level, new ArrayList<>());             map.get(curr.level).add(curr.node.data); Â
            if (curr.node.left != null )                 q.add( new TNode(curr.node.left, curr.level + 1 ));               if (curr.node.right != null )                 q.add( new TNode(curr.node.right, curr.level));         } Â
        for (Map.Entry<Integer, List<Integer> > entry : map.entrySet()) {             int k = entry.getKey(); Â
            List<Integer> l = map.get(k);             int size = l.size(); Â
            for ( int i = 0 ; i < l.size(); i++) {                 System.out.print(l.get(i));                 System.out.print( " " );             }             System.out.println( "" );         }         return ;     } Â
    // Driver code     public static void main(String[] args){         Node 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 ); Â
        diagonalPrint(root);     } } |
Python3
# Python Program to print diagonal traversal using queue Â
# Tree Node class Node:     def __init__( self , x):         self .data = x         self .left = None         self .right = None Â
Â
def diagonalPrint(root): Â Â Â Â if root is None : Â Â Â Â Â Â Â Â return Â
    q = []     q.append(root) Â
    while len (q) > 0 :         size = len (q)         answer = [] Â
        while size > 0 :             temp = q[ 0 ]             q.pop( 0 ) Â
            # traversing each component;             while temp is not None :                 answer.append(temp.data) Â
                if temp.left is not None :                     q.append(temp.left) Â
                temp = temp.right Â
            size - = 1 Â
        result.append(answer) Â
Â
if __name__ = = '__main__' : Â Â Â Â 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 ) Â
    result = [] Â
    diagonalPrint(root) Â
    for i in range ( len (result)):         for j in range ( len (result[i])):             print (result[i][j], end = " " )         print () Â
# This code is contributed by Tapesh(tapeshdua420) |
C#
// C# implementation of above approach Â
using System; using System.Collections.Generic; Â
public class Node { Â Â Â Â public int data; Â Â Â Â public Node left, right; Â
    public Node( int item)     {         data = item;         left = null ;         right = null ;     } } class GFG { Â
    static List<List< int > > result = new List<List< int > >();     static void printLevelOrder(Node root)     {         if (root == null )             return ;                Queue<Node> q = new Queue<Node>();         q.Enqueue(root); Â
        while (q.Count != 0) {                        int size = q.Count;             List< int > answer = new List< int >();                        while (size-- != 0) {                                  Node temp = q.Dequeue();                                // traversing each component;                 while (temp != null ) {                     answer.Add(temp.data); Â
                    if (temp.left != null )                         q.Enqueue(temp.left);                     temp = temp.right;                 }             }             result.Add(answer);         }     } Â
    // Driver code     public static void Main()     { Â
        Node 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); Â
        printLevelOrder(root);         for ( int i = 0; i < result.Count; i++) {             for ( int j = 0; j < result[i].Count; j++) {                 Console.Write(result[i][j]);                 Console.Write( " " );             }             Console.WriteLine();         }     } } Â
// This code is contributed by Abhijeet Kumar(abhijeet19403) |
Javascript
// javascript program for the above approach // structure of tree node class Node{ Â Â Â Â constructor(data){ Â Â Â Â Â Â Â Â this .data = data; Â Â Â Â Â Â Â Â this .left = null ; Â Â Â Â Â Â Â Â this .right = null ; Â Â Â Â } } Â
function newNode(data){ Â Â Â Â return new Node(data); } Â
let result = [] function diagonalPrint(root){     if (root == null ) return ;          q = [];     q.push(root);          while (q.length > 0){         let size = q.length;         answer = [];                  while (size--){             let temp = q.shift();                          // traversing each component             while (temp != null ){                 answer.push(temp.data);                                  if (temp.left != null )                     q.push(temp.left);                                  temp = temp.right;             }         }         result.push(answer);     } } Â
// driver code 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); Â
for (let i = 0; i < result.length; i++){ Â Â Â Â for (let j = 0; j < result[i].length; j++){ Â Â Â Â Â Â Â Â console.log(result[i][j] + " " ); Â Â Â Â } Â Â Â Â Â } Â
// this code is contributed by Kirti Agarwal(kirtiagarwal23121999) |
8 10 14 3 6 7 13 1 4
Time Complexity: O(N), because we are visiting nodes once.
Auxiliary Space: O(N), because we are using a queue.
This article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!