问题
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