1 -> 0
2 -> 1
3 -> 2
4 -> 2
5 -> 0
The tree node data structure has an int value and list of children tree nodes.
class TreeNode:
int value
IList children
//constructor
TreeNode(int value):
this.value = value
children = new List()
The code first traverses through the childParentMap hashmap to build the value->TreeNode hashmap 'valueNodeMap'. It traverses through it again to get child and parent values, their equivalent nodes and adds the child node to the parent node. The root node with value 0 is created separately (root of the tree).
TreeNode createTreeView(Hashmap childParentMap):
// build value->TreeNode map
Hashmap valueNodeMap = new Hashmap()
foreach (KeyValuePair kvPair in childParentMap):
int value = kvPair.Key
TreeNode node = new TreeNode(value)
if !valueNodeMap.ContainsKey(value):
valueNodeMap.Add(value, node)
// add root value 0 and root node to valueNodeMap
int rootValue = 0;
TreeNode rootNode = new TreeNode(rootValue);
valueNodeMap.Add(rootValue, rootNode);
// for child and parent values, find equivalent nodes and
// add child node as child to parent node
foreach (KeyValuePair kvPair in childParentMap):
int childValue = kvPair.Key
int parentValue = kvPair.Value
TreeNode childNode = valueNodeMap[childValue]
TreeNode parentNode = valueNodeMap[parentValue]
parentNode.children.Add(childNode)
// return root
return rootNode
Time is O(n).
There is a recursive solution too but it takes O(n^2) time.
The code is similar to building a graph from an adjacency list.
[H/T ai, as, sc, jf, se]

0 comments:
Post a Comment