LC199. Binary Tree Right Side View
#
Problem DescriptionSource: https://leetcode.com/problems/binary-tree-right-side-view/
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example: Given binary tree [1, 2, 3, null, 6, null, 4, null, null, 5],
return [1, 3, 4, 5].
#
BFS Solution#
High level strategyOur strategy to solve this problem is to conduct a breadth-first search. On each level, we traverse from the left to right, but only keeping the value of the right-most node. To implement this solution, we will make use of the index property of arrays. The index of every element in the resulting array is the level of the corresponding right-most node on the tree. To see this, one can simply flip the tree on its side. The time complexity of this solution is O(n), where 'n' is equal to the number of nodes. The space complexity of this solution is O(logn), or O(h), where 'h' is equal to the height of the tree.
#
Code- Javascript
- Python
#
DFS Solutions#
High level strategyWe can modify the code and covert it into a DFS solution, the same concept applies.
#
Code- Java
- Python
- C++