Binary Tree Right Side View Traversal

Day - 93 Binary Tree Right Side View The problem - Given the root of 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. Essentially, return the rightmost node at each level. Brute Force - Perform a complete level-order traversal storing all nodes at each level, then extract only the last node from each level. This gives O(n) time but stores all nodes unnecessarily, wasting O(n) space when we only need one node per level. Approach Used - •) Create result = new ArrayList<>(). •) If root == null, return empty result. •) Create queue = new LinkedList<>(). •) Add root to queue. •) While queue is not empty, 1 - Get current level size, size = queue.size(). 2 - For i = 0 to size - 1, - Poll node from queue, node = que.poll(). - ⁠If i == size - 1, add to result: result.add(current.val), this is the last node at current level. - ⁠If current.left != null, add to queue: queue.offer(current.left). - ⁠If current.right != null, add to queue: queue.offer(current.right). •) Return result. Complexity - Time - O(n), where n is number of nodes. Space - O(w), where w is maximum width of tree. Note - Use level-order BFS to traverse the tree level by level. By tracking the current level size, we can identify the last node processed in each level—this is the rightmost visible node. We only store this last node from each level, efficiently building the right side view in a single traversal. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving

  • text

To view or add a comment, sign in

Explore content categories