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.
Input : 1 / \ 2 3 / \ \ 4 5 6 Output : 1 2 4 Input : 1 / \ 2 3 \ 4 \ 5 \ 6 Output :1 2 4 5 6
The left view contains all nodes that are first nodes in their levels. A simple solution is to do level order traversal and print the first node in every level.
The problem can also be solved using simple recursive traversal. We can keep track of the level of a node by passing a parameter to all recursive calls. The idea is to keep track of the maximum level also. Whenever we see a node whose level is more than maximum level so far, we print the node because this is the first node in its level (Note that we traverse the left subtree before right subtree). Following is the implementation-
12 10 25
Time Complexity: The function does a simple traversal of the tree, so the complexity is O(n).
Auxiliary Space: O(n), due to the stack space during recursive call.
This article is contributed by Ramsai Chinthamani. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Iterative Method To Print Left View of a Binary Tree
- Sum of nodes in the left view of the given binary tree
- Check if the Left View of the given tree is sorted or not
- Print Right View of a Binary Tree
- Print Nodes in Top View of Binary Tree
- Print nodes in top view of Binary Tree | Set 2
- Print nodes in the Top View of Binary Tree | Set 3
- Print Bottom-Right View of a Binary Tree
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Print leaf nodes in binary tree from left to right using one stack
- Print all leaf nodes of a binary tree from right to left
- Print left and right leaf nodes separately in Binary Tree
- Print all leaf nodes of a Binary Tree from left to right
- Bottom View of a Binary Tree
- Right view of Binary Tree using Queue
- Sum of nodes in top view of binary tree
- Sum of nodes in the right view of the given binary tree
- Bottom View of a Binary Tree using Recursion
- Sum of nodes in bottom view of Binary Tree
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree