Given a Binary Tree, print Left view of it. Left view of a Binary Tree is set of nodes visible when tree is visited from Left side. The task is to complete the function leftView(), which accepts root of the tree as argument.
Left view of following tree is 1 2 4 8.
1 / \ 2 3 / \ / \ 4 5 6 7 \ 8
Example 1:
Input:
1
/ \\
3 2
Output:1 3
Example 2:
Input:
Output:10 20 40

Left View of Binary Tree | Practice | GeeksforGeeks
//Function to return a list containing elements of left view of the binary tree.
vector<int> leftView(Node *root)
{
vector<int> res;
unordered_set<int> s;
if(!root)
return res;
queue<pair<Node*,int>> q;
q.push({root,0});
while(!q.empty())
{
auto curr = q.front();
q.pop();
Node *node = curr.first;
int ht = curr.second;
if(s.find(ht)==s.end())
{
s.insert(ht);
res.push_back(node->data);
}
if(node->left)
q.push({node->left,ht+1});
if(node->right)
q.push({node->right,ht+1});
}
return res;
}