Binary tree right side view

What a tree looks like standing to its right: the last node visible on every level.

Time O(n)Space O(w)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

Run a level-order BFS and, on each level, keep only the last node dequeued. That node is the one standing farthest to the right on its level, since the queue always empties a level left to right. Collecting that one node per level, top to bottom, gives the sequence of nodes visible from the right side.

Code

public static List<int> RightSideView(TreeNode root) {
    var result = new List<int>();
    var queue = new Queue<TreeNode>();
    if (root != null) queue.Enqueue(root);
    while (queue.Count > 0) {
        int count = queue.Count;
        for (int i = 0; i < count; i++) {
            TreeNode node = queue.Dequeue();
            if (i == count - 1) result.Add(node.val);
            if (node.left != null) queue.Enqueue(node.left);
            if (node.right != null) queue.Enqueue(node.right);
        }
    }
    return result;
}

Tips

In the .NET library

The left side view is the exact mirror: either take the first node dequeued per BFS level, or do the DFS version visiting left before right.