Encode N-ary Tree to Binary Tree Problem
Description
LeetCode Problem 431.
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-nary tree structure.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See following example).
For example, you may encode the following 3-ary tree to a binary tree in this way:

Input: root = [1,null,3,2,4,null,5,6]
Note that the above is just an example which might or might not work. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Example 1:
Input: root = [1,null,3,2,4,null,5,6]
Output: [1,null,3,2,4,null,5,6]
Example 2:
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Example 3:
Input: root = []
Output: []
Constraints:
- The number of nodes in the tree is in the range
[0, 10^4]. 0 <= Node.val <= 10^4- 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. Your encode and decode algorithms should be stateless.
Solution
Approach: First Child, Next Sibling
A binary node has only two pointers, but an N-ary node can have any number of children. The children are in order, though, so every node needs just two links to reach them all: one to its first child and one to its next sibling. Those two links fit exactly into left and right.
encode(root). Make a binary node with root's value. Encode each child in turn. The first child's binary node becomes left, and each later child's binary node becomes the right of the child before it. The children of one node end up as a chain of right pointers that starts at that node's left.
For Example 1, node 1 gets left = 3, then 3.right = 2 and 2.right = 4. Node 3's own children hang below it as 3.left = 5 and 5.right = 6.
decode(root). Make an N-ary node with root's value. Start at root.left and follow right pointers. Each node on that chain is one child, which is decoded on its own and added to the list in the same order.
Nothing is lost. Each binary node's left leads to its own children and its right to its own next sibling, so every parent, child and sibling relation can be read back. A binary root never has a right, because the N-ary root has no siblings. The recursion only goes one level deeper per tree level, since siblings are handled by a loop. With a height of at most 1000 this is safe.
Complexity: O(n) time for both encode and decode, where n is the number of nodes. O(h) extra space for the recursion, where h ≤ 1000 is the height of the N-ary tree.
class Codec:
# Encodes an n-ary tree to a binary tree.
def encode(self, root: 'Optional[Node]') -> Optional[TreeNode]:
"""left = first child, right = next sibling."""
if root is None:
return None
node = TreeNode(root.val)
prev = None # the binary node of the previous child
for child in root.children or []:
encoded = self.encode(child)
if prev is None:
node.left = encoded # the first child hangs on the left
else:
prev.right = encoded # each later child is its older sibling's right
prev = encoded
return node
# Decodes your binary tree to an n-ary tree.
def decode(self, data: Optional[TreeNode]) -> 'Optional[Node]':
if data is None:
return None
node = Node(data.val, [])
child = data.left # the first child, then follow right pointers through its siblings
while child is not None:
node.children.append(self.decode(child))
child = child.right
return node