Algorithms

Recursive mapping: Right and Left views of Binary Trees

Apr 2026
7 min read

Visualizing a tree from the side requires more than just traversal; it requires tracking the 'first' or 'last' node seen at every vertical level of the structure.

Implementation

java
class Solution { // Right View: The last node seen at each level public List<Integer> rightSideView(TreeNode root) { List<Integer> result = new ArrayList<>(); solve(root, 0, result); return result; } private void solve(TreeNode node, int level, List<Integer> res) { if (node == null) return; // If this is the first time we've reached this depth, // it must be the right-most node if (level == res.size()) { res.add(node.val); } solve(node.right, level + 1, res); solve(node.left, level + 1, res); } }