Skip to the solution
EasyDSAAsked in 20247 min read

Object tree traversal

1.1k views

The problem

Problem, as an interviewer would state it: "Implement traverseTree(obj) — recursively walking a nested plain-object tree and collecting every LEAF value together with its own full dot-notation path."

Examples:

Code
traverseTree({a: 1, b: {c: 2}});
// [{path: "a", value: 1}, {path: "b.c", value: 2}]

Clarifying questions expected:

  • Should a real ARRAY value be treated as a leaf itself, or recursed into like a nested object — since arrays are genuinely objects too in JavaScript?
  • What real, correct format should the path take — a dot-separated string, or an array of keys?
  • Does the traversal need to visit keys in any particular real order (e.g. matching Object.keys's own order)?

Code / implementation expected: Yes — real, direct proof against a genuinely nested, multi-level tree, confirming correct leaf detection including the real array-as-leaf edge case.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: traverseTree() collects every leaf's exact path and value from a real nested tree, correctly treating a real array value as a single leaf

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 22 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Array Union

Continue