From 0e0548249f6bd65a9ae335798b279d4882b6c63e Mon Sep 17 00:00:00 2001 From: shweta-kansal <72966734+shweta-kansal@users.noreply.github.com> Date: Sun, 3 Oct 2021 20:16:08 +0530 Subject: [PATCH] Create top_view of binary tree.cpp --- top_view of binary tree.cpp | 65 +++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 top_view of binary tree.cpp diff --git a/top_view of binary tree.cpp b/top_view of binary tree.cpp new file mode 100644 index 0000000..7b2f5ea --- /dev/null +++ b/top_view of binary tree.cpp @@ -0,0 +1,65 @@ +//Top view in binary tree----set of nodes visible when the tree is viewed from the top + +// 1 +// / \ +// 2 3 +// / \ / \ +// 4 5 6 7 +// here top view is 4 2 1 3 7 + +// iterative approach -- using queue +#include +using namespace std; +typedef long long int ll; + +struct node{ + int data; + struct node*left; + struct node*right; +// constructor + node(int val){ + data=val; + left=right=NULL; + } +}; + +void topview(struct node*root){ + queue>q; + mapmp; + q.push({root,0}); + while(!q.empty()){ +struct node*curr=q.front().first; +int dist=q.front().second; +q.pop(); +if(mp.count(dist)==0){ + + mp[dist]=curr->data; +} +if(curr->left!=NULL){ + q.push({curr->left,dist-1}); +} + +if(curr->right!=NULL){ + q.push({curr->right,dist+1}); +} + } + +for(auto i:mp){ + cout<left= new node(2); + root->right=new node(7); + root->left->left=new node(3); + root->left->right= new node(4); + root->left->right->left= new node(5); + root->left->right->right= new node(6); + + topview(root); + +return 0; +}