I have some data(Python list
of dict
s) which looks like:
[
{\'value\': \'A\', \'level\': 0},
{\'value\': \'B\', \'level\':
The code should be simple. Your scheme implies there is an order to the children, so I will use a list
.
In [8]: class Node:
...: def __init__(self, val=None):
...: self.value = val
...: self.children = []
...: def __repr__(self):
...: return "<Node {}>".format(self.value)
...:
The algorithm is also simple. Start at the root. Iterate over the data. While you are less than "level"
nodes deep, continue moving down the children going to the last child appended attempting to go down the last node in children. If attempting to index into the last child fails, then we know we are where we have to be (assuming the input is well behaved!) and we append a new node with the value "value"
. If you don't fail and make it to "level"
, append a new node with the value "value"
. Return to the root and repeat while you are not done iterating over the data.
In [9]: root = Node()
In [10]: for record in data:
...: last = root
...: for _ in range(record['level']):
...: last = last.children[-1]
...: last.children.append(Node(record['value']))
...:
Now, to check out our tree:
In [12]: root.children
Out[12]: [<Node A>, <Node G>]
In [13]: root.children[0].children
Out[13]: [<Node B>, <Node D>]
In [14]: root.children[0].children[1].children
Out[14]: [<Node E>, <Node F>]
In [15]: root.children[1].children
Out[15]: [<Node H>]
In [16]: root.children[1].children[0].children
Out[16]: []
Using your handy print_tree
function:
In [24]: def print_tree(root, depth=0):
...: for child in root.children:
...: print(' ' * depth + '%r' % child)
...: print_tree(child, depth + 1)
...:
In [25]: print_tree(root)
<Node A>
<Node B>
<Node C>
<Node D>
<Node E>
<Node F>
<Node G>
<Node H>