Problem
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.
For example, you may encode the following 3-ary
tree to a binary tree in this way:
graph LR subgraph Original[" "] A(1) A --- B(3) A --- C(2) A --- D(4) B --- E(5) B --- F(6) end subgraph Encoded[" "] A2(1) A2 --- B2(3) A2 --- C2(2) B2 --- E2(5) B2 ~~~ N2:::hidden C2 ~~~ N1:::hidden C2 --- D2(4) E2 ~~~ N3:::hidden E2 --- F2(6) end Original --> Encoded classDef hidden display:none
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.
Note:
N
is in the range of[1, 1000]
- Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
Examples
Example 1
|
|
Example 2
|
|
Solution
Method 1 - DFS
Encoding an N-ary tree into a binary tree involves transforming the structure of the tree while preserving the connectivity. The approach can involve two main transformations:
- Left-child/right-sibling representation:
- The first child of a node becomes the left child in the binary tree.
- Subsequent children become the right child of the previous child, forming a sibling chain.
- Decoding:
- Reverse the transformation by reconstructing the N-ary tree from the binary tree.
This encoding effectively maintains the N-ary relationships while conforming to the binary tree structure.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
. We traverse all nodes once in a DFS manner. Thus, both processes haveO(n)
complexity, wheren
is the total number of nodes. - 🧺 Space complexity:
O(h)
. The space used for recursion (call stack) in DFS traversal is proportional to the height of the tree. Hence, it isO(h)
whereh
is the height of the tree.