PPractick

DSA interview question

Binary Tree Representation in Java

Easy · Data structures · Topics: tree, java

The problem

A Java service receives binary trees from a web client as level-order arrays with nulls (the format LeetCode uses, like [1, 2, 3, null, 5]) and must turn them into real linked nodes, then send results back in the same format. Write the Node class (value plus left and right references), a build method that constructs the tree from the level-order array with a queue, and a serialize method that writes a tree back out in level order, trimming trailing nulls. It's the everyday plumbing behind every tree problem.

Example: [1, 2, 3, null, 5] → a tree whose preorder is 1 2 5 3, and which serialises back to [1, 2, 3, null, 5].

Function signature

static class Node { int data; Node left, right; }
static Node build(Integer[] level);           // null marks a missing child
static List<Integer> serialize(Node root);    // level order, trailing nulls removed

Test cases

Input (level order)OutputExplanation
[1, 2, 3, null, 5][1, 2, 3, null, 5] preorder [1, 2, 5, 3]2 has only a right child
[][] preorder []Empty tree
[1, null, 2, 3][1, null, 2, 3] preorder [1, 2, 3]
[5][5] preorder [5]
[1, 2, 3, 4, 5, 6, 7][1, 2, 3, 4, 5, 6, 7] preorder [1, 2, 4, 5, 3, 6, 7]A perfect tree

(Confirm: children of a null are not listed in the array (LeetCode convention); serialisation removes trailing nulls so it round-trips exactly.)

How interviewers phrase it

Clarifying questions to ask

  1. Which input format? (A LeetCode-style level order, where null children of null nodes are omitted.)
  2. Should serialisation trim trailing nulls? (Yes, to round-trip exactly.)
  3. Are values int or generic? (int here; generics are a small change.)

Follow-ups to expect

  1. "Why a queue when building?"
  2. "Why can't ArrayDeque hold the nulls during serialisation?"
  3. "Array representation instead of nodes?"
  4. "How would you serialise with preorder instead?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in