Encode N-ary Tree to Binary Tree Problem Statement

You are provided with an N-ary tree constituted of 'N' nodes, where node '1' is the head of the tree. Your task is to encode this N-ary tree into a binary tree in such a way that it can fully restore the original N-ary tree from the encoded binary tree. Additionally, include functions to decode a given binary tree back into the N-ary tree format.

Input:

The first line indicates the number of test cases, 'T'.
The subsequent lines consist of tree elements in a level-order manner, separated by a single space.

Output:

For each test case:
- Encode function: Return the binary tree.
- Decode function: Return the N-ary tree.

Example:

Input:
N-ary Tree represented as:-
6
1 -1 2 3 4 -1 5 -1 6 -1 -1 -1 -1
Output:
Encoded Binary Tree (level-order):-
1
2 -1
5 3
-1 -1 6 4
-1 -1 -1 -1

Constraints:

  • 1 <= T <= 10
  • 1 <= N <= 1000
  • Time Limit: 1 sec

Note:

  • The N-ary Tree is described in a level-order traversal form, with each child group separated by -1.
  • The binary tree is stored in a list/array containing 'N' + 1 elements, indexed from 1 to 'N'. Each element holds the left child followed by the right child, separated by lines.
  • Display -1 where a node lacks a left or right child.
  • No need for explicit output printing in the implementation; focus on the function logic.
AnswerBot
1y

The task is to encode an N-ary tree into a binary tree and then decode the binary tree back into the original N-ary tree.

  • Encode the N-ary tree by representing each node as a binary tree node with its ...read more

Help your peers!
Add answer anonymously...
JUSPAY Front end Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter