Problem
Given the root
of a binary tree, imagine yourself standing on the left side of it. Return the values of the nodes you can see ordered from top to bottom.
What is Left View of a Binary Tree?
When just look at the tree from the left side , all the nodes you can see will be the left view of the tree.
Examples
Example 1:
|
|
Solution
This problem is similar to Binary Tree Right Side View. The left view of a binary tree can be obtained by traversing the tree level-by-level (using a level order traversal) and collecting the first node at each level.
Method 1 - Use the Level Change Indication and Recursing on Left First
- Traverse the tree from left to right
- Print the first node you encounter
- Take two variables , currentLevel=0 and nextLevel=1
- As soon as you change level , change the currentLevel = nextLevel
- Print only when
current level<nextLevel
so this way you will print only the first element - For rest of the nodes on the the level currentLevel and nextLevel are equal so it wont print
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
- wheren
is the number of nodes in the binary tree. Each node is visited once. - 🧺 Space complexity:
O(n)
- due to the storage of nodes in the queue used for level order traversal.