![]() |
VOOZH | about |
Prerequisite: Generic Trees(N-array Trees)
In this article, we will discuss the conversion of the Generic Tree to a Binary Tree. Following are the rules to convert a Generic(N-array Tree) to a Binary Tree:
Examples:
Convert the following Generic Tree to Binary Tree:
:
Note: If the parent node has only the right child in the general tree then it becomes the rightmost child node of the last node following the parent node in the binary tree. In the above example, if node B has the right child node L then in binary tree representation L would be the right child of node D.
Below are the steps for the conversion of Generic Tree to Binary Tree:
1 2 6 7 3 4 5 8 9
Time Complexity: O(n)
Auxiliary Space: O(h)
Approach-2:-Converting a generic tree to a binary tree using a pre-order traversal
The first approach involves converting a generic tree to a binary tree using a pre-order traversal. The steps involved in this approach are as follows:
Create a binary tree node with the data of the current node in the generic tree.
Set the left child of the binary tree node to be the result of recursively converting the first child of the current node in the generic tree.
Set the right child of the binary tree node to be the result of recursively converting the next sibling of the current node in the generic tree.
Return the binary tree node.
The time complexity of this approach is O(n), where n is the number of nodes in the generic tree.
Here's the main function for this approach:
1 2 6 7 3 4 5 8 9
Time Complexity : O(N)
Auxiliary Space : O(N)