LeetCode 199: Binary Tree Right Side View Solution

Master LeetCode problem 199 (Binary Tree Right Side View), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

199. Binary Tree Right Side View

Problem Explanation

Explanation:

  • We can solve this problem using a level order traversal of the binary tree while keeping track of the rightmost node at each level.
  • At each level of the tree, the rightmost node will be the last node encountered during the level order traversal.
  • We can implement this by using a queue for level order traversal and updating the result array with the rightmost node at each level.

Solution Code

import java.util.*;

class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        
        while (!queue.isEmpty()) {
            int size = queue.size();
            int rightValue = 0;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                rightValue = node.val;
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            result.add(rightValue);
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 199 (Binary Tree Right Side View)?

This page provides optimized solutions for LeetCode problem 199 (Binary Tree Right Side View) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 199 (Binary Tree Right Side View)?

The time complexity for LeetCode 199 (Binary Tree Right Side View) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 199 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 199 in Java, C++, or Python.

Back to LeetCode Solutions