Encode N-ary Tree to Binary Tree - Problem

Design an algorithm to encode an N-ary tree into a binary tree and decode the binary tree to get the original N-ary tree.

An N-ary tree is a rooted tree in which each node has no more than N children. Similarly, a binary tree is a rooted tree in which each node has no more than 2 children.

There is no restriction on how your encode/decode algorithm should work. You just need to ensure that an N-ary tree can be encoded to a binary tree and this binary tree can be decoded to the original N-ary tree structure.

Note: You need to implement both encode and decode methods in a single class called Codec.

Input & Output

Example 1 — Basic N-ary Tree
$ Input: root = [1,null,3,2,4,null,5,6]
Output: [1,null,3,2,4,null,5,6]
💡 Note: N-ary tree with root 1 having children [3,2,4], node 3 having children [5,6]. After encode-decode, the structure is preserved exactly.
Example 2 — Single Node
$ Input: root = [1]
Output: [1]
💡 Note: Single node tree remains unchanged after encoding and decoding process.
Example 3 — Empty Tree
$ Input: root = []
Output: []
💡 Note: Empty tree (null root) returns empty array after encode-decode operations.

Constraints

  • The number of nodes in the tree is in the range [0, 104]
  • 0 ≤ Node.val ≤ 104
  • The height of the N-ary tree is less than or equal to 1000
  • Do not use class member/global/static variables to store states

Visualization

Tap to expand
Encode N-ary Tree to Binary Tree Overview1324N-ary TreeENCODE1324Binary TreeDECODE1324Restored N-ary✓ Perfect reconstruction of original structureTime: O(n) | Space: O(h)
Understanding the Visualization
1
Input N-ary Tree
Tree where nodes can have multiple children
2
Encode to Binary
Transform using first-child-next-sibling mapping
3
Decode Back
Reconstruct original N-ary structure
Key Takeaway
🎯 Key Insight: Map N-ary relationships to binary using first-child-next-sibling pattern
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
28.5K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen