R Tree With n Branches

帅比萌擦擦* 提交于 2019-12-10 22:12:25

问题


How can I generate a tree with n nodes, each of which have m number of children, with the condition that each child node is obtained by fun(parent)?

I've gleaned some logic from this post, but I am stuck on how to generate up to n names, and also how to generate the functions for assigning newly generated children to their parents recursively. (insert utopian joke here)

-Edit-

I've attempted using TheTime's solution below, and this certainly answered this question. However, I didn't ask the question I intended. Because this question has a good answer that could be useful in certain circumstances, I've posted a new question that asks what I really meant here.


回答1:


Recursion is one way, alternatively you could use a 'stack' data structure. I'm not sure what kind of function you are thinking of using or what sort of values you plan on storing, so here is simply a function that creates a child node's name using its parent's name as well.

## Function to apply to nodes to create children
nodeNamer <- function() {
    i <- 0
    function(node) sprintf("%s -> %g", node$name, (i <<- i+1))
}

make_tree <- function(depth, m, fn) {
    root <- Node$new('root')

    ## Some helper function to recurse
    f <- function(node, depth) {
        if (depth <= 0) return( root )
        for (i in seq.int(m)) {
            val <- fn(node)  # apply some function to parent node
            child <- node$AddChild(val)
            Recall(child, depth-1)  # recurse, Recall refers to 'f'
        }
    }
    f(root, depth)
    return( root )
}

## Make a tree with depth of '2' and 3 branches from each node
## Note that the way I defined the naming function, you must call it 
## in order to reset the the counter to 0
res <- make_tree(2, 3, nodeNamer())

res
#                  levelName
# 1  root                   
# 2   ¦--root -> 1          
# 3   ¦   ¦--root -> 1 -> 2 
# 4   ¦   ¦--root -> 1 -> 3 
# 5   ¦   °--root -> 1 -> 4 
# 6   ¦--root -> 5          
# 7   ¦   ¦--root -> 5 -> 6 
# 8   ¦   ¦--root -> 5 -> 7 
# 9   ¦   °--root -> 5 -> 8 
# 10  °--root -> 9          
# 11      ¦--root -> 9 -> 10
# 12      ¦--root -> 9 -> 11
# 13      °--root -> 9 -> 12


来源:https://stackoverflow.com/questions/33768841/r-tree-with-n-branches

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!