Leetcode #431: Encode N-ary Tree to Binary Tree
In this guide, we solve Leetcode #431 Encode N-ary Tree to Binary Tree in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: Yes
- Tags: Tree, Depth-First Search, Breadth-First Search, Design, Binary Tree
Intuition
We need to explore a structure deeply before backing up, which suits DFS.
DFS keeps local context on the call stack and is easy to implement recursively.
Approach
Define a recursive DFS that carries the necessary state.
Combine child results as the recursion unwinds.
Steps:
- Define a recursive DFS with state.
- Visit children and combine results.
- Return the final aggregation.
Example
Input: root = [1,null,3,2,4,null,5,6]
Python Solution
"""
# 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 root is None:
return None
node = TreeNode(root.val)
if not root.children:
return node
left = self.encode(root.children[0])
node.left = left
for child in root.children[1:]:
left.right = self.encode(child)
left = left.right
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, [])
if data.left is None:
return node
left = data.left
while left:
node.children.append(self.decode(left))
left = left.right
return node
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(root))
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.