KatInterview

771. Encode N-ary Tree to Binary Tree

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core of this problem is to design a pair of algorithms, encode and decode, to convert an N-ary tree into a binary tree and vice-versa. The key challenge lies in representing a variable number of children from an N-ary node using only the left and right pointers of a binary tree node, while ensuring the transformation is perfectly reversible.

Solution

Encode N-ary Tree to Binary Tree in Python

"""
# Definition for a Node.
class Node:
    def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
        self.val = val
        self.children = children
"""

"""
# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
"""

class Codec:
    # Encodes an n-ary tree to a binary tree.
    def encode(self, root: 'Optional[Node]') -> Optional[TreeNode]:
        if not root:
            return None

        # Create the corresponding binary tree node.
        b_node = TreeNode(root.val)

        # If the N-ary node has children...
        if root.children:
            # The first child becomes the left child of the binary node.
            b_node.left = self.encode(root.children[0])

            # The rest of the children become a right-linked list starting from the left child.
            current_sibling = b_node.left
            for i in range(1, len(root.children)):
                current_sibling.right = self.encode(root.children[i])
                current_sibling = current_sibling.right
        
        return b_node

	# Decodes your binary tree to an n-ary tree.
    def decode(self, data: Optional[TreeNode]) -> 'Optional[Node]':
        if not data:
            return None

        # Create the corresponding N-ary node.
        n_node = Node(data.val, [])

        # The left child of the binary node is the first child of the N-ary node.
        # The subsequent right children in the binary tree are siblings.
        current_b_child = data.left
        while current_b_child:
            # Decode the child and add it to the children list.
            n_node.children.append(self.decode(current_b_child))
            # Move to the next sibling.
            current_b_child = current_b_child.right
        
        return n_node

# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(root))

Encode N-ary Tree to Binary Tree in Java

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

class Codec {
    // Encodes an n-ary tree to a binary tree.
    public TreeNode encode(Node root) {
        if (root == null) {
            return null;
        }

        // Create the corresponding binary tree node.
        TreeNode bNode = new TreeNode(root.val);

        // If the N-ary node has children...
        if (root.children != null && !root.children.isEmpty()) {
            // The first child becomes the left child of the binary node.
            bNode.left = encode(root.children.get(0));

            // The rest of the children become a right-linked list starting from the left child.
            TreeNode currentSibling = bNode.left;
            for (int i = 1; i < root.children.size(); i++) {
                currentSibling.right = encode(root.children.get(i));
                currentSibling = currentSibling.right;
            }
        }

        return bNode;
    }

    // Decodes your binary tree to an n-ary tree.
    public Node decode(TreeNode root) {
        if (root == null) {
            return null;
        }

        // Create the corresponding N-ary node.
        Node nNode = new Node(root.val, new ArrayList<Node>());

        // The left child of the binary node is the first child of the N-ary node.
        // The subsequent right children in the binary tree are siblings.
        TreeNode currentBChild = root.left;
        while (currentBChild != null) {
            // Decode the child and add it to the children list.
            nNode.children.add(decode(currentBChild));
            // Move to the next sibling.
            currentBChild = currentBChild.right;
        }

        return nNode;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(root));

Encode N-ary Tree to Binary Tree in C++

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Codec {
public:
    // Encodes an n-ary tree to a binary tree.
    TreeNode* encode(Node* root) {
        if (!root) {
            return nullptr;
        }

        // Create the corresponding binary tree node.
        TreeNode* bNode = new TreeNode(root->val);

        // If the N-ary node has children...
        if (!root->children.empty()) {
            // The first child becomes the left child of the binary node.
            bNode->left = encode(root->children[0]);

            // The rest of the children become a right-linked list starting from the left child.
            TreeNode* currentSibling = bNode->left;
            for (size_t i = 1; i < root->children.size(); ++i) {
                currentSibling->right = encode(root->children[i]);
                currentSibling = currentSibling->right;
            }
        }

        return bNode;
    }

    // Decodes your binary tree to an n-ary tree.
    Node* decode(TreeNode* root) {
        if (!root) {
            return nullptr;
        }

        // Create the corresponding N-ary node.
        Node* nNode = new Node(root->val);

        // The left child of the binary node is the first child of the N-ary node.
        // The subsequent right children in the binary tree are siblings.
        TreeNode* currentBChild = root->left;
        while (currentBChild) {
            // Decode the child and add it to the children list.
            nNode->children.push_back(decode(currentBChild));
            // Move to the next sibling.
            currentBChild = currentBChild->right;
        }

        return nNode;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.decode(codec.encode(root));

Encode N-ary Tree to Binary Tree in TypeScript

/**
 * Definition for _Node.
 * class _Node {
 *     val: number
 *     children: _Node[]
 *     
 *     constructor(v: number) {
 *         this.val = v;
 *         this.children = [];
 *     }
 * }
 */


/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

// The problem statement in TypeScript uses `serialize` and `deserialize` for method names.
// Renaming `_Node` to `NaryNode` for clarity, assuming the test environment handles the mapping.
// If not, use `_Node` as required.
class Codec {
    // Encodes an n-ary tree to a binary tree.
    encode(root: _Node | null): TreeNode | null {
        if (!root) {
            return null;
        }

        // Create the corresponding binary tree node.
        const bNode = new TreeNode(root.val);

        // If the N-ary node has children...
        if (root.children && root.children.length > 0) {
            // The first child becomes the left child of the binary node.
            bNode.left = this.encode(root.children[0]);

            // The rest of the children become a right-linked list starting from the left child.
            let currentSibling = bNode.left;
            for (let i = 1; i < root.children.length; i++) {
                if (currentSibling) {
                    currentSibling.right = this.encode(root.children[i]);
                    currentSibling = currentSibling.right;
                }
            }
        }

        return bNode;
    }

    // Decodes your binary tree to an n-ary tree.
    decode(root: TreeNode | null): _Node | null {
        if (!root) {
            return null;
        }

        // Create the corresponding N-ary node.
        const nNode = new _Node(root.val);

        // The left child of the binary node is the first child of the N-ary node.
        // The subsequent right children in the binary tree are siblings.
        let currentBChild = root.left;
        while (currentBChild) {
            // Decode the child and add it to the children list.
            nNode.children.push(this.decode(currentBChild)!); // We know it's not null inside the loop.
            // Move to the next sibling.
            currentBChild = currentBChild.right;
        }

        return nNode;
    }
}

// Your Codec object will be instantiated and called as such:
// var codec = new Codec();
// codec.decode(codec.encode(root));

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.