具有n个分支的R树 [英] R Tree With n Branches
问题描述
我如何生成一个具有n个节点的树,每个节点有m个子节点,而每个子节点都可以通过fun(parent)获得?
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)?
我从这篇文章中收集了一些逻辑,但我仍然坚持如何生成最多n个名字,以及如何生成将新生成的子代递归给其父母的函数. (在此处插入乌托邦笑话)
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)
-编辑-
我尝试使用下面的TheTime解决方案,这肯定回答了这个问题.但是,我没有问我想要的问题.由于此问题有一个很好的答案,在某些情况下可能会有用.因此,我发布了一个新问题,询问我的真实含义
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.
推荐答案
递归是一种方法,也可以使用堆栈"数据结构.我不确定您打算使用哪种函数或打算存储哪种值,因此这里只是一个函数,它也使用其父节点的名称来创建子节点的名称.
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
这篇关于具有n个分支的R树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!