-
Notifications
You must be signed in to change notification settings - Fork 89
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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
1 parent
28a7829
commit 38ae9b8
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |