Skip to content

Commit

Permalink
Create diagonalViewBinaryTree
Browse files Browse the repository at this point in the history
The following code takes the input of a Binary Tree as an array and prints the diagonal view of the tree. It uses a queue for implementation of the same.
Example Input:
14 
8 3 10 1 -1 6 14 -1 -1 -1 -1 4  7 3
Output:
8 10 14 
3 6 7 13 
1 4
  • Loading branch information
maitreyi0505 authored Oct 6, 2020
1 parent 28a7829 commit 38ae9b8
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions CPP/Binary Tree/diagonalViewBinaryTree
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#include <bits/stdc++.h>
using namespace std;
void diagonalview(int tree[], int n)
{
if(n==0) //if tree is empty
return;

queue<int> q;
q.push(0); //push root
q.push(-1); //push delimiter
int i=0; //posn of current element left at 2i+1 right at 2i+2

while(q.front()!=-1){ //while the queue has elements

while(q.front()!=-1 )//for each element in queue before the delimiter
{
i=q.front();
q.pop();
while(i<n && tree[i]!=-1){ //for each right child that exists
cout<<tree[i]<<" ";
if(i*2+1<n&&i*2+1!=-1) //check and push left child
{
q.push(i*2+1);
}
i=i*2+2; //move to right child
}
}
q.pop(); //remove delimiter(-1) from front
cout<<endl;

q.push(-1); //add delimiter
}

}
int main() {

int n;
cin>>n;
int tree[n];
for(int i=0;i<n;i++)
cin>>tree[i];

diagonalview(tree, n);
return 0;
}

0 comments on commit 38ae9b8

Please sign in to comment.