-2

I want to construct a dynamic tree. The initial state of the tree only has a root node, then, I hope it can add nodes level by level. These added nodes are fetched according to some additional functions. I have found some similary questions in Stack Overflow, such as How do I build a tree dynamically in Python How do I build a tree dynamically in Python, but the answers don't satisfy my need and the originer.

  • Why don't the answers satisfy your need? They literally do what you want? – Jason Chia Feb 14 '20 at 10:31
  • beaucse the answers should specify all paths beforehand. I want to build the first level, and if I have a child node of that, build another level, ...etc. – qiang liu Feb 14 '20 at 11:05

1 Answers1

0

From the answer of the question

import collections
from functools import reduce 

def add_element(root, path, data):
    if len(path) == 1:
        root[path[0]] = data
    else:
        add_element(root[path[0]], path[1:], data)

tree = lambda: collections.defaultdict(tree)
root = tree()

add_element(root,["top"],{}) #Make a level
add_element(root,["top","level1"],{}) # Make another level
add_element(root,["top","level1","val"],2) #Data
print(root)

As I mentioned, it does do what you want it to do.

Community
  • 1
  • 1
Jason Chia
  • 1,144
  • 1
  • 5
  • 18