Left View of Binary Tree
Problem
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
Solution Approach
Expected Time complexity:
Click - to see solution code
- C++
map<int, vector<int>> mp;
void traversal(Node *root, int h) {
if (!root) return;
mp[h].push_back(root->data);
traversal(root->left, h + 1);
traversal(root->right, h + 1);
}
vector<int> leftView(Node *root) {
vector<int> view;
traversal(root, 0);
for (int i = 0; i < mp.size(); i++) {
view.push_back(mp[i][0]);
}
mp.clear();
return view;
}