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.
Using Recursion and Hashmap - O(n) Time and O(n) Space:
To find the diagonal view of a binary tree, we perform a recursive traversal that stores nodes in a hashmap based on their diagonal levels. Left children increase the diagonal level, while right children remain on the same level.
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;}};// Recursive function to print diagonal viewvoiddiagonalRecur(Node*root,intlevel,unordered_map<int,vector<int>>&levelData){// Base caseif(root==nullptr)return;// Append the current node into hash map.levelData[level].push_back(root->data);// Recursively traverse the left subtree.diagonalRecur(root->left,level+1,levelData);// Recursively traverse the right subtree.diagonalRecur(root->right,level,levelData);}// function to print diagonal viewvector<int>diagonal(Node*root){vector<int>ans;// Create a hash map to store each// node at its respective level.unordered_map<int,vector<int>>levelData;diagonalRecur(root,0,levelData);intlevel=0;// Insert into answer level by level.while(levelData.find(level)!=levelData.end()){vector<int>v=levelData[level];for(intj=0;j<v.size();j++){ans.push_back(v[j]);}level++;}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{// Recursive function to print diagonal viewstaticvoiddiagonalRecur(Noderoot,intlevel,HashMap<Integer,ArrayList<Integer>>levelData){// Base caseif(root==null)return;// Append the current node into hash map.levelData.computeIfAbsent(level,k->newArrayList<>()).add(root.data);// Recursively traverse the left subtree.diagonalRecur(root.left,level+1,levelData);// Recursively traverse the right subtree.diagonalRecur(root.right,level,levelData);}// function to print diagonal viewstaticArrayList<Integer>diagonal(Noderoot){ArrayList<Integer>ans=newArrayList<>();// Create a hash map to store each// node at its respective level.HashMap<Integer,ArrayList<Integer>>levelData=newHashMap<>();diagonalRecur(root,0,levelData);intlevel=0;// Insert into answer level by level.while(levelData.containsKey(level)){ArrayList<Integer>v=levelData.get(level);ans.addAll(v);level++;}returnans;}staticvoidprintList(ArrayList<Integer>v){for(intval:v){System.out.print(val+" ");}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=diagonal(root);printList(ans);}}
Python
# Python program to print diagonal viewclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Recursive function to print diagonal viewdefdiagonalRecur(root,level,levelData):# Base caseifrootisNone:return# Append the current node into hash map.iflevelnotinlevelData:levelData[level]=[]levelData[level].append(root.data)# Recursively traverse the left subtree.diagonalRecur(root.left,level+1,levelData)# Recursively traverse the right subtree.diagonalRecur(root.right,level,levelData)# function to print diagonal viewdefdiagonal(root):ans=[]# Create a hash map to store each# node at its respective level.levelData={}diagonalRecur(root,0,levelData)level=0# Insert into answer level by level.whilelevelinlevelData:ans.extend(levelData[level])level+=1returnansdefprintList(v):print(" ".join(map(str,v)))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(root)printList(ans)
C#
// C# program to print diagonal viewusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Recursive function to print diagonal viewstaticvoidDiagonalRecur(Noderoot,intlevel,Dictionary<int,List<int>>levelData){// Base caseif(root==null)return;// Append the current node into hash map.if(!levelData.ContainsKey(level)){levelData[level]=newList<int>();}levelData[level].Add(root.data);// Recursively traverse the left subtree.DiagonalRecur(root.left,level+1,levelData);// Recursively traverse the right subtree.DiagonalRecur(root.right,level,levelData);}// function to print diagonal viewstaticList<int>Diagonal(Noderoot){List<int>ans=newList<int>();// Create a hash map to store each// node at its respective level.Dictionary<int,List<int>>levelData=newDictionary<int,List<int>>();DiagonalRecur(root,0,levelData);intlevel=0;// Insert into answer level by level.while(levelData.ContainsKey(level)){ans.AddRange(levelData[level]);level++;}returnans;}staticvoidPrintList(List<int>v){foreach(intiinv){Console.Write(i+" ");}Console.WriteLine();}staticvoidMain(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);List<int>ans=Diagonal(root);PrintList(ans);}}
JavaScript
// JavaScript program to print diagonal viewclassNode{constructor(x){this.key=x;this.left=null;this.right=null;}}// Recursive function to print diagonal viewfunctiondiagonalRecur(root,level,levelData){// Base caseif(root===null)return;// Append the current node into hash map.if(!levelData[level]){levelData[level]=[];}levelData[level].push(root.key);// Recursively traverse the left subtree.diagonalRecur(root.left,level+1,levelData);// Recursively traverse the right subtree.diagonalRecur(root.right,level,levelData);}// function to print diagonal viewfunctiondiagonal(root){letans=[];// Create a hash map to store each// node at its respective level.letlevelData={};diagonalRecur(root,0,levelData);letlevel=0;// Insert into answer level by level.while(levelinlevelData){ans=ans.concat(levelData[level]);level++;}returnans;}functionprintList(v){console.log(v.join(" "));}// 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=diagonal(root);printList(ans);
Output
8 10 14 3 6 7 13 1 4
Time Complexity: O(n), where n is the number of nodes in the binary tree. Auxiliary Space: O(n), used in hash map.
Note: This approach may get time limit exceeded(TLE) error as it is not an optimized approach. For optimized approach, Please refer to Iterative diagonal traversal of binary tree