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 INPUT: N-ary Tree 1 3 2 4 5 6 [1,null,3,2,4,null,5,6] Each node can have N children ALGORITHM STEPS 1 First Child Rule Left child = first child 2 Next Sibling Rule Right child = next sibling 3 Recursive Encode Apply rules to all nodes 4 Decode Reverse Reverse rules to decode Encoding Map: parent.left = firstChild node.right = nextSibling Decoding Map: children[0] = node.left sibling = node.right Time: O(n) | Space: O(n) for both encode/decode FINAL RESULT: Binary Tree 1 3 5 6 2 4 Binary Tree Rules: Left edge = first child link Right edge = sibling link [1,null,3,2,4,null,5,6] OK - Reversible encoding! Decode restores original tree Key Insight: The "First Child - Next Sibling" representation converts any N-ary tree to binary tree by using left pointer for first child and right pointer for next sibling. This encoding is bijective (one-to-one), meaning every N-ary tree maps to exactly one binary tree and vice versa, enabling perfect reconstruction. TutorialsPoint - Encode N-ary Tree to Binary Tree | First Child - Next Sibling Approach
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