Java solution based on level order traversal.


  • 0
    J

    Here is simple Java solution that traverse the binary tree level by level and adds the node to the result list whenever it is the last on the given level.

    public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        if (root == null) {
            return Collections.emptyList();
        }
    
        final List<Integer> result = new LinkedList<Integer>();
        final Deque<TreeNode> queue = new LinkedList<TreeNode>();
        queue.addLast(root);
        int count = 1;
    
        while (!queue.isEmpty()) {
            TreeNode node = queue.pollFirst();
            count--;
    
            if (node.left != null) {
                queue.addLast(node.left);
            }
            if (node.right != null) {
                queue.addLast(node.right);
            }
    
            if (count == 0) {
                result.add(node.val);
                count = queue.size();
            }
        }
        return result;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.