Test Case Generation | Set 6 (Random Unweighted Binary Tree)
Generating Random Unweighted Binary Tree:
- Since this is a tree, the test data generation plan is such that no cycle gets formed.
- The number of edges is one less than the number of vertices.
- For each RUN, first print the count of nodes say, N and the next N – 1 lines are of the form (a, b) where a is the parent of b.
- Each node contains at most 2 children.
Approach: The problem can be solved using Queue. The idea is to traverse the tree using BFS. Follow the steps below to solve the problem:
- Initialize a map, say mp to check if a node is already included in the tree or not.
- Initialize a queue to store the nodes at each level of the tree.
- Consider 1 as root node and insert it into the queue.
- Iterate over the queue while the total count of nodes in the tree not equal to N. In every iteration insert distinct nodes of each level of the tree into the queue using rand() function and the map, also insert the node and the parent of the node into an array
- Finally, print the value of N and the array.
5 5 4 1 2 1 3 3 5
Time Complexity : O(N log N)
Auxiliary Space : O(N)
My Personal Notes arrow_drop_up
Please Login to comment...