765. Serialize and Deserialize N-ary Tree
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 problem requires us to design an algorithm to serialize an N-ary tree into a string and deserialize it back to its original structure. An N-ary tree is a tree where each node can have a variable number of children. The core challenge is to encode the tree's structure (parent-child relationships) and node values into a linear string format in a way that can be perfectly reversed.
Solution
Serialize and Deserialize N-ary Tree in Python
"""
# Definition for a Node.
class Node(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children if children is not None else []
"""
import collections
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string.
:type root: Node
:rtype: str
"""
if not root:
return ""
parts = []
# Helper function for pre-order traversal
def preorder(node):
if not node:
return
# Append node's value and number of children
parts.append(str(node.val))
parts.append(str(len(node.children)))
# Recursively serialize children
for child in node.children:
preorder(child)
preorder(root)
return " ".join(parts)
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree.
:type data: str
:rtype: Node
"""
if not data:
return None
tokens = collections.deque(data.split(' '))
# Helper function to build the tree recursively
def build():
# Read value and number of children
val = int(tokens.popleft())
num_children = int(tokens.popleft())
node = Node(val)
# Recursively build child nodes
for _ in range(num_children):
node.children.append(build())
return node
return build()
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
Serialize and Deserialize N-ary 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;
}
};
*/
class Codec {
// Encodes a tree to a single string.
public String serialize(Node root) {
if (root == null) {
return "";
}
List<String> parts = new ArrayList<>();
serializeHelper(root, parts);
return String.join(" ", parts);
}
private void serializeHelper(Node node, List<String> parts) {
if (node == null) {
return;
}
// Add node's value and number of children
parts.add(String.valueOf(node.val));
parts.add(String.valueOf(node.children.size()));
// Recursively serialize children
for (Node child : node.children) {
serializeHelper(child, parts);
}
}
// Decodes your encoded data to tree.
public Node deserialize(String data) {
if (data.isEmpty()) {
return null;
}
String[] tokens = data.split(" ");
Queue<String> queue = new LinkedList<>(Arrays.asList(tokens));
return deserializeHelper(queue);
}
private Node deserializeHelper(Queue<String> queue) {
// Read value and number of children
int val = Integer.parseInt(queue.poll());
int numChildren = Integer.parseInt(queue.poll());
Node node = new Node(val, new ArrayList<>());
// Recursively build child nodes
for (int i = 0; i < numChildren; i++) {
node.children.add(deserializeHelper(queue));
}
return node;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
Serialize and Deserialize N-ary 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;
}
};
*/
#include <sstream>
#include <functional>
class Codec {
public>
// Encodes a tree to a single string.
string serialize(Node* root) {
if (!root) {
return "";
}
stringstream ss;
// Helper function for pre-order traversal
function<void(Node*)> preorder = [&](Node* node) {
if (!node) return;
// Append node's value and number of children
ss << node->val << " ";
ss << node->children.size() << " ";
// Recursively serialize children
for (Node* child : node->children) {
preorder(child);
}
};
preorder(root);
return ss.str();
}
// Decodes your encoded data to tree.
Node* deserialize(string data) {
if (data.empty()) {
return nullptr;
}
stringstream ss(data);
// Helper function to build the tree recursively
function<Node*()> build = [&]() -> Node* {
string val_str, size_str;
ss >> val_str >> size_str;
int val = stoi(val_str);
int size = stoi(size_str);
Node* node = new Node(val);
// Recursively build child nodes
for (int i = 0; i < size; ++i) {
node->children.push_back(build());
}
return node;
};
return build();
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
Serialize and Deserialize N-ary Tree in TypeScript
/**
* Definition for _Node.
* class _Node {
* val: number
* children: _Node[]
*
* constructor(val?: number, children?: _Node[]) {
* this.val = (val===undefined ? 0 : val)
* this.children = (children===undefined ? [] : children)
* }
* }
*/
class Codec {
constructor() {}
// Encodes a tree to a single string.
serialize(root: _Node | null): string {
if (!root) {
return "";
}
const parts: string[] = [];
// Helper function for pre-order traversal
const preorder = (node: _Node | null) => {
if (!node) {
return;
}
// Append node's value and number of children
parts.push(String(node.val));
parts.push(String(node.children.length));
// Recursively serialize children
for (const child of node.children) {
preorder(child);
}
};
preorder(root);
return parts.join(' ');
}
// Decodes your encoded data to tree.
deserialize(data: string): _Node | null {
if (data === "") {
return null;
}
const tokens = data.split(' ');
const queue: string[] = [...tokens];
// Helper function to build the tree recursively
const build = (): _Node | null => {
if (queue.length === 0) {
return null;
}
// Read value and number of children
const val = parseInt(queue.shift()!);
const numChildren = parseInt(queue.shift()!);
const node = new _Node(val);
// Recursively build child nodes
for (let i = 0; i < numChildren; i++) {
const child = build();
if (child) {
node.children.push(child);
}
}
return node;
};
return build();
}
}
// Your Codec object will be instantiated and called as such:
// var codec = new Codec()
// codec.deserialize(codec.serialize(root))
More Hard LeetCode answers
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.