Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close

    Coding problem

    Read a tree level by level

    MediumAbout 25 minFull AccessLearn it: Tree Traversals in C#: Recursive and Iterative DFS, BFS Level Order and Stack Depth

    The task

    An org chart is stored as a binary tree, and the intranet shows it one level per row: the head first, then their direct reports, and so on.

    Complete LevelValues(TreeNode? root). Return the tree's values level by level, the top level first and each level from left to right. An empty tree (null) gives an empty list. The TreeNode class is given; do not change it.

    Signature

    public static List<List<int>> LevelValues(TreeNode? root)

    Examples

    • tree [1, 2, 3, 4, 5, 6, 7] → [[1], [2, 3], [4, 5, 6, 7]]. A full tree of three levels.
    • tree [1, 2, 3, null, 4, null, 5] → [[1], [2, 3], [4, 5]]. 4 is the right child of 2, and 5 the right child of 3.

    Limits: Up to 5,000 nodes. Trees are written level by level, with null for a missing child.

    The tests check: an empty tree, one node, chains to the left and to the right, negative values, a full tree of 1,023 nodes (10 levels), and a chain of 1,000 nodes.

    Hints

      Your code

      C#Solution.csLoading the editor…

      Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;

      // A node of a binary tree. Do not change this class: the tests build trees with it.
      public sealed class TreeNode
      {
          public int Val;
          public TreeNode? Left;
          public TreeNode? Right;
      
          public TreeNode(int val, TreeNode? left = null, TreeNode? right = null)
          {
              Val = val;
              Left = left;
              Right = right;
          }
      }
      
      public static class Solution
      {
          // Returns the values level by level, each level from left to right.
          public static List<List<int>> LevelValues(TreeNode? root)
          {
              throw new NotImplementedException();
          }
      }

      This problem comes with TechInterviewNotes Full Access

      Unlock all paid content on TechInterviewNotes.