Left View of Binary Tree
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
c++ implementation:
void leftView(Node *root)
{ queue<Node*> q;
if (root == NULL)
return;
q.push(root);
q.push(NULL);
while (!q.empty()) {
Node* temp = q.front();
if (temp) {
cout<< temp->data<<" ";
while (q.front() != NULL) {
if (temp->left)
q.push(temp->left);
if (temp->right)
q.push(temp->right);
q.pop();
temp = q.front();
}
q.push(NULL);
}
q.pop();
}
}
Time Complexity: O(n)
No comments