Given a Binary Tree, the task is to print the diagonal traversal of the binary tree. Note: If the diagonal element are present in two different subtrees, then left subtree diagonal element should be taken first and then right subtree.
Example:
Input:
Output: 8 10 14 3 6 7 13 1 4 Explanation: The above is the diagonal elements in a binary tree that belong to the same line.
[Expected Approach - 1] Using Queue with delimiter - O(n) Time and O(n) Space
The idea is to traverse the binary tree in level order manner using a queue. Push the root node and null pointer into the queue. For each node (starting from root), append its value to the resultant list. Push its left child node into queue if it exists, and set it to its right child node. If the current node is null, it means the starting of the next diagonal. So set the current node to the front node of the queue and pop from queue.
Below is the implementation of the above approach:
C++
// C++ program to print diagonal view#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Iterative function to print diagonal viewvector<int>diagonal(Node*root){vector<int>ans;// base caseif(root==nullptr)returnans;queue<Node*>q;q.push(root);q.push(nullptr);while(!q.empty()){Node*curr=q.front();q.pop();// if current is delimiter then insert another// null for next diagonal if(curr==nullptr){// if tree has been traversedif(q.empty())break;q.push(nullptr);}// Else print the current diagonalelse{while(curr!=nullptr){ans.push_back(curr->data);// if left child is present // push into queueif(curr->left!=nullptr)q.push(curr->left);// current equals to right childcurr=curr->right;}}}returnans;}voidprintList(vector<int>v){intn=v.size();for(inti=0;i<n;i++){cout<<v[i]<<" ";}cout<<endl;}intmain(){// Create a hard coded tree// 8// / \ // 3 10// / / \ // 1 6 14// / \ /// 4 7 13Node*root=newNode(8);root->left=newNode(3);root->right=newNode(10);root->left->left=newNode(1);root->right->left=newNode(6);root->right->right=newNode(14);root->right->right->left=newNode(13);root->right->left->left=newNode(4);root->right->left->right=newNode(7);vector<int>ans=diagonal(root);printList(ans);}
Java
// Java Program to print diagonal viewimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Iterative function to print diagonal viewstaticArrayList<Integer>diagonalPrint(Noderoot){ArrayList<Integer>ans=newArrayList<>();// base caseif(root==null)returnans;Queue<Node>q=newLinkedList<>();q.add(root);q.add(null);while(!q.isEmpty()){Nodecurr=q.poll();// if current is delimiter then insert another// null for next diagonalif(curr==null){// if tree has been traversedif(q.isEmpty())break;q.add(null);}// Else print the current diagonalelse{while(curr!=null){ans.add(curr.data);// if left child is present// push into queueif(curr.left!=null)q.add(curr.left);// current equals to right childcurr=curr.right;}}}returnans;}staticvoidprintList(ArrayList<Integer>v){for(inti=0;i<v.size();i++){System.out.print(v.get(i)+" ");}System.out.println();}publicstaticvoidmain(String[]args){// Create a hard coded tree// 8// / \// 3 10// / / \// 1 6 14// / \ /// 4 7 13Noderoot=newNode(8);root.left=newNode(3);root.right=newNode(10);root.left.left=newNode(1);root.right.left=newNode(6);root.right.right=newNode(14);root.right.right.left=newNode(13);root.right.left.left=newNode(4);root.right.left.right=newNode(7);ArrayList<Integer>ans=diagonalPrint(root);printList(ans);}}
Python
# Python Program to print diagonal viewclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Iterative function to print diagonal viewdefdiagonal_print(root):ans=[]ifrootisNone:returnansq=[]q.append(root)q.append(None)whilelen(q)>0:curr=q.pop(0)# if current is delimiter then insert another# null for next diagonalifcurrisNone:# if tree has been traversediflen(q)==0:breakq.append(None)# Else print the current diagonalelse:whilecurrisnotNone:ans.append(curr.data)# if left child is present# push into queueifcurr.leftisnotNone:q.append(curr.left)# current equals to right childcurr=curr.rightreturnansdefprint_list(v):foriinrange(len(v)):print(v[i],end=" ")print()if__name__=="__main__":# Create a hard coded tree# 8# / \# 3 10# / / \# 1 6 14# / \ /# 4 7 13root=Node(8)root.left=Node(3)root.right=Node(10)root.left.left=Node(1)root.right.left=Node(6)root.right.right=Node(14)root.right.right.left=Node(13)root.right.left.left=Node(4)root.right.left.right=Node(7)ans=diagonal_print(root)print_list(ans)
C#
// C# Program to print diagonal viewusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Iterative function to print diagonal viewstaticList<int>DiagonalPrint(Noderoot){List<int>ans=newList<int>();// base caseif(root==null)returnans;Queue<Node>q=newQueue<Node>();q.Enqueue(root);q.Enqueue(null);while(q.Count>0){Nodecurr=q.Dequeue();// if current is delimiter then insert another// null for next diagonalif(curr==null){// if tree has been traversedif(q.Count==0)break;q.Enqueue(null);}// Else print the current diagonalelse{while(curr!=null){ans.Add(curr.data);// if left child is present// push into queueif(curr.left!=null)q.Enqueue(curr.left);// current equals to right childcurr=curr.right;}}}returnans;}staticvoidPrintList(List<int>v){for(inti=0;i<v.Count;i++){Console.Write(v[i]+" ");}Console.WriteLine();}staticvoidMain(){// Create a hard coded tree// 8// / \// 3 10// / / \// 1 6 14// / \ /// 4 7 13Noderoot=newNode(8);root.left=newNode(3);root.right=newNode(10);root.left.left=newNode(1);root.right.left=newNode(6);root.right.right=newNode(14);root.right.right.left=newNode(13);root.right.left.left=newNode(4);root.right.left.right=newNode(7);List<int>ans=DiagonalPrint(root);PrintList(ans);}}
JavaScript
// JavaScript Program to print diagonal viewclassNode{constructor(x){this.key=x;this.left=null;this.right=null;}}// Iterative function to print diagonal viewfunctiondiagonalPrint(root){letans=[];// base caseif(root===null)returnans;letq=[];// push rootq.push(root);// push delimiterq.push(null);while(q.length>0){letcurr=q.shift();// if current is delimiter then insert another// null for next diagonalif(curr===null){// if tree has been traversedif(q.length===0)break;q.push(null);}// Else print the current diagonalelse{while(curr!==null){ans.push(curr.key);// if left child is present// push into queueif(curr.left!==null)q.push(curr.left);// current equals to right childcurr=curr.right;}}}returnans;}functionprintList(v){for(leti=0;i<v.length;i++){process.stdout.write(v[i]+" ");}console.log();}// Create a hard coded tree// 8// / \// 3 10// / / \// 1 6 14// / \ /// 4 7 13letroot=newNode(8);root.left=newNode(3);root.right=newNode(10);root.left.left=newNode(1);root.right.left=newNode(6);root.right.right=newNode(14);root.right.right.left=newNode(13);root.right.left.left=newNode(4);root.right.left.right=newNode(7);letans=diagonalPrint(root);printList(ans);
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)
[Expected Approach - 2] Using Queue without delimiter - O(n) Time and O(n) Space
if(curr.left != null), then add it to the queue and move curr pointer to right of curr.
if curr = null, then remove a node from queue.
Below is the implementation of the above approach:
C++
// C++ program to print diagonal view#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Iterative function to print diagonal viewvector<int>diagonalPrint(Node*root){vector<int>ans;// base caseif(root==nullptr)returnans;queue<Node*>q;// push rootq.push(root);while(!q.empty()){Node*curr=q.front();q.pop();while(curr!=nullptr){ans.push_back(curr->data);// if left child is present // push into queueif(curr->left!=nullptr)q.push(curr->left);// current equals to right childcurr=curr->right;}}returnans;}voidprintList(vector<int>v){intn=v.size();for(inti=0;i<n;i++){cout<<v[i]<<" ";}cout<<endl;}intmain(){// Create a hard coded tree// 8// / \ // 3 10// / / \ // 1 6 14// / \ /// 4 7 13Node*root=newNode(8);root->left=newNode(3);root->right=newNode(10);root->left->left=newNode(1);root->right->left=newNode(6);root->right->right=newNode(14);root->right->right->left=newNode(13);root->right->left->left=newNode(4);root->right->left->right=newNode(7);vector<int>ans=diagonalPrint(root);printList(ans);}
Java
// Java Program to print diagonal viewimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Iterative function to print diagonal viewstaticArrayList<Integer>diagonalPrint(Noderoot){ArrayList<Integer>ans=newArrayList<>();// base caseif(root==null)returnans;Queue<Node>q=newLinkedList<>();// push rootq.add(root);while(!q.isEmpty()){Nodecurr=q.poll();while(curr!=null){ans.add(curr.data);// if left child is present// push into queueif(curr.left!=null)q.add(curr.left);// current equals to right childcurr=curr.right;}}returnans;}staticvoidprintList(ArrayList<Integer>v){for(inti=0;i<v.size();i++){System.out.print(v.get(i)+" ");}System.out.println();}publicstaticvoidmain(String[]args){// Create a hard coded tree// 8// / \// 3 10// / / \// 1 6 14// / \ /// 4 7 13Noderoot=newNode(8);root.left=newNode(3);root.right=newNode(10);root.left.left=newNode(1);root.right.left=newNode(6);root.right.right=newNode(14);root.right.right.left=newNode(13);root.right.left.left=newNode(4);root.right.left.right=newNode(7);ArrayList<Integer>ans=diagonalPrint(root);printList(ans);}}
Python
# Python Program to print diagonal viewclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Iterative function to print diagonal viewdefdiagonal_print(root):ans=[]# base caseifrootisNone:returnansq=[]# push rootq.append(root)whilelen(q)>0:curr=q.pop(0)whilecurrisnotNone:ans.append(curr.data)# if left child is present# push into queueifcurr.leftisnotNone:q.append(curr.left)# current equals to right childcurr=curr.rightreturnansdefprint_list(v):foriinrange(len(v)):print(v[i],end=" ")print()if__name__=="__main__":# Create a hard coded tree# 8# / \# 3 10# / / \# 1 6 14# / \ /# 4 7 13root=Node(8)root.left=Node(3)root.right=Node(10)root.left.left=Node(1)root.right.left=Node(6)root.right.right=Node(14)root.right.right.left=Node(13)root.right.left.left=Node(4)root.right.left.right=Node(7)ans=diagonal_print(root)print_list(ans)
C#
// C# Program to print diagonal viewusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Iterative function to print diagonal viewstaticList<int>DiagonalPrint(Noderoot){List<int>ans=newList<int>();// base caseif(root==null)returnans;Queue<Node>q=newQueue<Node>();// push rootq.Enqueue(root);while(q.Count>0){Nodecurr=q.Dequeue();while(curr!=null){ans.Add(curr.data);// if left child is present// push into queueif(curr.left!=null)q.Enqueue(curr.left);// current equals to right childcurr=curr.right;}}returnans;}staticvoidPrintList(List<int>v){for(inti=0;i<v.Count;i++){Console.Write(v[i]+" ");}Console.WriteLine();}staticvoidMain(){// Create a hard coded tree// 8// / \// 3 10// / / \// 1 6 14// / \ /// 4 7 13Noderoot=newNode(8);root.left=newNode(3);root.right=newNode(10);root.left.left=newNode(1);root.right.left=newNode(6);root.right.right=newNode(14);root.right.right.left=newNode(13);root.right.left.left=newNode(4);root.right.left.right=newNode(7);List<int>ans=DiagonalPrint(root);PrintList(ans);}}
JavaScript
// JavaScript Program to print diagonal viewclassNode{constructor(x){this.key=x;this.left=null;this.right=null;}}// Iterative function to print diagonal viewfunctiondiagonalPrint(root){letans=[];// base caseif(root===null)returnans;letq=[];// push rootq.push(root);while(q.length>0){letcurr=q.shift();while(curr!==null){ans.push(curr.key);// if left child is present// push into queueif(curr.left!==null)q.push(curr.left);// current equals to right childcurr=curr.right;}}returnans;}functionprintList(v){for(leti=0;i<v.length;i++){process.stdout.write(v[i]+" ");}console.log();}// Create a hard coded tree// 8// / \// 3 10// / / \// 1 6 14// / \ /// 4 7 13letroot=newNode(8);root.left=newNode(3);root.right=newNode(10);root.left.left=newNode(1);root.right.left=newNode(6);root.right.right=newNode(14);root.right.right.left=newNode(13);root.right.left.left=newNode(4);root.right.left.right=newNode(7);letans=diagonalPrint(root);printList(ans);
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)