Back to DSA

Binary Tree Right Side View

medium
Acceptance: 52%
Binary Tree

Picture yourself looking at a binary tree from the right side. Report the node values you would see at each depth level, ordered from the top of the tree to the bottom.

Examples

Example 1:
Input:root = [1,2,3,4,null,null,5]
Output:[1,3,5]
Example 2:
Input:root = [8,null,6]
Output:[8,6]

Hints

00:00
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();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (i == size - 1) result.add(node.val);
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
        }
        return result;
    }
}
Time complexityO(n)
Space complexityO(n)