Start learning free

LESSON 215 OF 314 · BINARY TREES

Binary Tree Right Side View in C#: Level-Order Traversal with a Queue

Practice O(n) Read the full explanation

You get the root of a binary tree. Imagine you stand to its right and look at it. Return the values you can see, from the top row down.

On each row, you see only the node farthest to the right. It hides the others. If the right side is shorter, lower rows show nodes from the left side. For an empty tree, return an empty array.

In the examples, each tree is written row by row from the top. Each row goes left to right. null marks a missing child.

 

Example 1:

      6
     / \
    3   8
   /   /
  2   7

Input: root = [6,3,8,2,null,7]
Output: [6,8,7]
Explanation: The last node of each row is 6, then 8, then 7.
The 3 and the 2 hide behind them.

Example 2:

      5
     / \
    9   2
     \
      4
     /
    7

Input: root = [5,9,2,null,4,null,null,7]
Output: [5,2,4,7]
Explanation: The right side ends at 2.
Further down, 4 and 7 are alone on their rows.
So you see them, even though they sit under 9.

 

Constraints:

  • The tree has 0 to 100 nodes.
  • Each value is a whole number from -100 to 100.
  • A value can appear more than once.

Note:

The tutorial walks the tree level by level with a queue. The queue starts with the root. At the start of each round it holds exactly one level: count its nodes, take them out one by one from the front, and put each node's children (left, then right) at the back, where they wait for the next round. The last node taken out in a round is the rightmost node of its level: that is the one you see.

Each node enters and leaves the queue once, so the time is O(n) for a tree of n nodes. The queue holds at most about two levels at a time, which is O(n) extra space in the worst case.

STEP 1 OF 11
    Ctrl + Enter to check

    C# · BINARY TREES

    Binary Tree Right Side View in C#, explained

    Problem overview

    The method RightSideView receives the root of a binary tree and returns a List<int>: the values you would see standing on the right side of the tree, from the top level down. From the right you see exactly one node per level, the rightmost one. An empty tree (root == null) shows nothing, so the result is an empty list.

    The lesson provides the TreeNode class, with the fields val, left and right and a constructor TreeNode(int x). For the tree [1,2,3,null,5,null,4], level order with null for a missing child, the levels are 1, then 2 3, then 5 4. The rightmost nodes are 1, 3 and 4, and the method returns [1,3,4]. For [1,2,3,4] the last level holds only 4, which sits under the left child. Nothing hides it, so it is visible and the answer is [1,3,4] again.

    Approach: walk the tree one level at a time

    The tempting shortcut is to follow right pointers from the root. It works only when every level has a right-hand node. On [1,2,3,4] it returns [1,3] and misses the 4, and on [1,2,null,3] it returns just [1], while the correct answer is [1,2,3]. The visible node is the last node of a level, whichever subtree it belongs to.

    So the method needs to look at the tree level by level. A Queue<TreeNode> does this. It is first in, first out: Enqueue adds at the back, Dequeue removes from the front, and Count says how many nodes wait inside. The idea is a loop in which each pass handles one whole level:

    • At the start of a pass, the queue holds exactly the nodes of one level, left to right, and nothing else.
    • Take the size of the queue first. That is the number of nodes in this level.
    • Remove that many nodes. The last one removed is the rightmost of the level, so its value goes into the result.
    • While removing a node, put its children at the back, left child first. They form the next level, and they wait behind the rest of this one.

    Because the size is read before the inner loop starts, the children added during the pass do not extend it. They are handled in the next pass of the while loop.

    Step by step

    1. Create the result list. A List<int> named result collects one value per level.
    2. Handle the empty tree. If root == null, return the empty list. The queue below needs a first node to start from, and putting null into it would crash later on node.left.
    3. Create the queue and enqueue root.
    4. Loop while queue.Count > 0. Each pass of this loop is one level.
    5. Store levelSize = queue.Count. This fixes how many nodes belong to the level.
    6. Loop i from 0 to levelSize - 1. This visits exactly the nodes of the level.
    7. Dequeue a node. The nodes leave in left-to-right order.
    8. Record the last one. When i == levelSize - 1, the node is the last of its level, so add node.val to result.
    9. Enqueue the left child, then the right child, each only if it is not null. Left first keeps every level in left-to-right order.
    10. Return result after the loops.

    The solution in C#

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

    The C# details worth knowing:

    • Queue<T> lives in System.Collections.Generic, like List<T>. Dequeue() on an empty queue throws an InvalidOperationException. The outer loop condition guarantees it never happens here.
    • Reading queue.Count once. Inside the for loop the count keeps changing as nodes leave and children arrive. Writing i < queue.Count in the loop header would mix levels together and make the "last node" test meaningless. Store the size in a variable before the loop.
    • Reference types and null. TreeNode is a class, so left and right are references that are null when the child is missing. That is why every child is tested before it is enqueued.
    • The list is built in level order, so the first level's value comes first. No reversing is needed.

    Complexity

    Time: O(n) for a tree of n nodes. Each node is enqueued once and dequeued once, and each takes constant work.

    Space: O(n). The queue holds at most two neighbouring levels at a time, and a level can hold about half of the nodes in a full tree. The result list adds one value per level, which is at most n.

    Edge cases and common mistakes

    • Empty tree. Returns an empty list.
    • Single node. [7] gives [7].
    • Left-leaning tree. [1,2,null,3] gives [1,2,3]: every node is the only one on its level, and every one is visible.
    • Following only right children. It returns [1,3] for [1,2,3,4] and misses the 4.
    • Using the queue size inside the loop header. The levels blur together: on [1,2,3,null,5,null,4] the method returns [3].
    • Enqueueing the right child first. The last node of a level would then be the leftmost one, so the method would report the left view instead of the right view.
    • Forgetting the null checks. A leaf has two null children, and enqueueing them makes the next Dequeue hand back null, so node.left throws a NullReferenceException.

    Testing

    • [1,2,3,null,5,null,4] gives [1,3,4].
    • [1,2,3,4] gives [1,3,4].
    • [] gives [].
    • [1,null,3] gives [1,3].
    • [1,2,null,3] gives [1,2,3].
    • [7] gives [7].
    • [1,2,3,4,5,6,7] gives [1,3,7].
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free