We have discussed recursive solution in below post. Diagonal Traversal of Binary Tree In this post, iterative solution is discussed. The idea is to use a queue to store only the left child of current node. After printing the data of current node make the current node to its right child, if present. A delimiter NULL is used to mark the starting of next diagonal.
Below is the implementation of above approach.
C++
/* C++ program to construct string from binary tree*/
#include <bits/stdc++.h>
usingnamespacestd;
/* A binary tree node has data, pointer to left
child and a pointer to right child */
structNode {
intdata;
Node *left, *right;
};
/* Helper function that allocates a new node */
Node* newNode(intdata)
{
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->left = node->right = NULL;
return(node);
}
// Iterative function to print diagonal view
voiddiagonalPrint(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
intmain()
{
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
importjava.util.*;
classsolution
{
// A binary tree node has data, pointer to left
// child and a pointer to right child
staticclassNode {
intdata;
Node left, right;
};
// Helper function that allocates a new node
staticNode newNode(intdata)
{
Node node = newNode();
node.data = data;
node.left = node.right = null;
return(node);
}
// Iterative function to print diagonal view
staticvoiddiagonalPrint(Node root)
{
// base case
if(root == null)
return;
// inbuilt queue of Treenode
Queue<Node> q= newLinkedList<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
publicstaticvoidmain(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
classNode:
def__init__(self,data):
self.val =data
self.left =None
self.right =None
# Function to print diagonal view
defdiagonalprint(root):
# base case
ifroot isNone:
return
# queue of treenode
q =[]
# Append root
q.append(root)
# Append delimiter
q.append(None)
whilelen(q) > 0:
temp =q.pop(0)
# If current is delimiter then insert another
# for next diagonal and cout nextline
ifnottemp:
# If queue is empty then return
iflen(q) ==0:
return
# Print output on nextline
print(' ')
# append delimiter again
q.append(None)
else:
whiletemp:
print(temp.val, end =' ')
# If left child is present
# append into queue
iftemp.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
usingSystem;
usingSystem.Collections;
classGFG
{
// A binary tree node has data,
// pointer to left child and
// a pointer to right child
publicclassNode
{
publicintdata;
publicNode left, right;
};
// Helper function that
// allocates a new node
staticNode newNode(intdata)
{
Node node = newNode();
node.data = data;
node.left = node.right = null;
return(node);
}
// Iterative function to print diagonal view
staticvoiddiagonalPrint(Node root)
{
// base case
if(root == null)
return;
// inbuilt queue of Treenode
Queue q = newQueue();
// 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
publicstaticvoidMain(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
functionnewNode(data)
{
let node = newNode(data);
return(node);
}
// Iterative function to print diagonal view
functiondiagonalPrint(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
Method: Without using 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:
Java
importjava.util.Queue;
importjava.util.LinkedList;
//Node
classNode{
intdata;
Node left;
Node right;
//Constructor for initializing the value of the node along with
//left and right pointers
Node(intdata){
this.data = data;
left = right = null;
}
}
publicclassDiagonalTraversal {
//root node
Node root = null;
//function to print in diagonal order
voidtraverse() {
//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 = newLinkedList<>();
//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
publicstaticvoidmain(String args[]) {
DiagonalTraversal tree = newDiagonalTraversal();
/* 8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13 */
//construction of the tree
tree.root = newNode(8);
tree.root.left = newNode(3);
tree.root.right = newNode(10);
tree.root.left.left = newNode(1);
tree.root.left.right = newNode(6);
tree.root.right.right = newNode(14);
tree.root.right.right.left = newNode(13);
tree.root.left.right.left = newNode(4);
tree.root.left.right.right = newNode(7);
//function call
tree.traverse();
}
}
//This method is contributed by Likhita AVL
C#
usingSystem;
usingSystem.Collections.Generic;
// Node
publicclassNode
{
publicintdata;
publicNode left;
publicNode right;
// Constructor for initializing the value
// of the node along with left and right pointers
publicNode(intdata)
{
this.data = data;
left = right = null;
}
}
publicclassDiagonalTraversal{
// Root node
Node root = null;
// Function to print in diagonal order
voidtraverse()
{
// 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 = newQueue<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
staticpublicvoidMain()
{
DiagonalTraversal tree = newDiagonalTraversal();
/* 8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13 */
// Construction of the tree
tree.root = newNode(8);
tree.root.left = newNode(3);
tree.root.right = newNode(10);
tree.root.left.left = newNode(1);
tree.root.left.right = newNode(6);
tree.root.right.right = newNode(14);
tree.root.right.right.left = newNode(13);
tree.root.left.right.left = newNode(4);
tree.root.left.right.right = newNode(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
functiontraverse()
{
// 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 = 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);
// function call
traverse();
// This code is contributed by avanitrachhadiya2155
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy