I have an unordered array of nodes. Each node has an id and parent_id. I want to pretty print out the nodes in an expanded format.
Assumptions:
There is only one root node in the array.
Don't worry about the white space.
Node has a toString() method.
All the ids are arbitrary and unique.
This is a tree and not a graph.
For example:
Sample input:
[{parentId: F, id:G}, {parentId: E, id: F}, {parentId: A, id: B}...]
A (parent_id = null)
B (parent_id = A)
C (parent_id = B)
D (parent_id = C)
H (parent_id = B)
E (parent_id = A)
F (parent_id = E)
G (parent_id = F)
Sample output:
ABCDHEFG
Please write a more optimized solution and tell me the complexity.
C++ version using recursion. First I sort the elements by parent: O(nlogn). Then I do a binary search O(logn) to find each parent on the list and recursively print it's children.
Output:
Code:
- Diego Giagio November 26, 2013