Encode N-ary Tree to Binary Tree

hard tree design

Problem

Design encode and decode functions to convert an n-ary tree to a binary tree and back losslessly.

InputN-ary: 1 → [3, 2, 4]; 3 → [5, 6]
Outputbinary: root.left = 3; 3.left = 5; 5.right = 6; 3.right = 2; 2.right = 4.
Children become a chain hanging off the left child via right-sibling links.

class Codec:
    def encode(self, root):
        if not root: return None
        b = BinaryNode(root.val)
        if root.children:
            b.left = self.encode(root.children[0])
        cur = b.left
        for child in root.children[1:]:
            cur.right = self.encode(child)
            cur = cur.right
        return b
    def decode(self, root):
        if not root: return None
        n = Node(root.val, [])
        cur = root.left
        while cur:
            n.children.append(self.decode(cur))
            cur = cur.right
        return n
class Codec {
  encode(root) {
    if (!root) return null;
    const b = { val: root.val, left: null, right: null };
    if (root.children.length) b.left = this.encode(root.children[0]);
    let cur = b.left;
    for (let i = 1; i < root.children.length; i++) {
      cur.right = this.encode(root.children[i]);
      cur = cur.right;
    }
    return b;
  }
  decode(root) {
    if (!root) return null;
    const n = { val: root.val, children: [] };
    let cur = root.left;
    while (cur) { n.children.push(this.decode(cur)); cur = cur.right; }
    return n;
  }
}
class Codec {
    public TreeNode encode(Node root) {
        if (root == null) return null;
        TreeNode b = new TreeNode(root.val);
        if (!root.children.isEmpty()) b.left = encode(root.children.get(0));
        TreeNode cur = b.left;
        for (int i = 1; i < root.children.size(); i++) {
            cur.right = encode(root.children.get(i));
            cur = cur.right;
        }
        return b;
    }
    public Node decode(TreeNode root) {
        if (root == null) return null;
        Node n = new Node(root.val, new ArrayList<>());
        TreeNode cur = root.left;
        while (cur != null) { n.children.add(decode(cur)); cur = cur.right; }
        return n;
    }
}
class Codec {
public:
    TreeNode* encode(Node* root) {
        if (!root) return nullptr;
        TreeNode* b = new TreeNode(root->val);
        if (!root->children.empty()) b->left = encode(root->children[0]);
        TreeNode* cur = b->left;
        for (int i = 1; i < (int)root->children.size(); i++) {
            cur->right = encode(root->children[i]);
            cur = cur->right;
        }
        return b;
    }
    Node* decode(TreeNode* root) {
        if (!root) return nullptr;
        Node* n = new Node(root->val, {});
        TreeNode* cur = root->left;
        while (cur) { n->children.push_back(decode(cur)); cur = cur->right; }
        return n;
    }
};
Time: O(n) Space: O(n)