【问题标题】:R Tree With n Branches具有 n 个分支的 R 树
【发布时间】:2015-11-17 23:10:40
【问题描述】:

如何生成n个节点的树,每个节点有m个子节点,条件是每个子节点都由fun(parent)获得?

我从this post 中收集到了一些逻辑,但我被困在如何生成最多 n 个名称,以及如何生成函数以递归地将新生成的孩子分配给他们的父母。 (在这里插入乌托邦笑话)

-编辑-

我尝试使用 TheTime 下面的解决方案,这肯定回答了这个问题。但是,我没有问我想要的问题。因为这个问题有一个很好的答案,在某些情况下可能会有用,所以我发布了一个新问题,询问我的真正意思 here

【问题讨论】:

    标签: r recursion tree logic


    【解决方案1】:

    递归是一种方法,或者您可以使用“堆栈”数据结构。我不确定您正在考虑使用哪种函数或计划存储哪种值,所以这里只是一个使用父节点名称创建子节点名称的函数。

    ## 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
    

    【讨论】:

    • 你最近救了我的培根 - 感谢你的帮助。这段代码完全符合我的要求,但是,这不是我想要的!我在我的问题中做得很糟糕,即每个节点的子节点数量实际上会有所不同。我已经尝试重建您编写的脚本 - 我遇到了一些障碍。我真的很想从一个父值开始,比如x
    • 真实的故事 - 这就是我因为过于笼统(而且太累)而得到的。这是新问题stackoverflow.com/questions/33772031/…。非常感谢您的帮助。
    • 我对这些论坛的礼仪有点新,但我正在接受它(很像 R 编程)。新帖子更具描述性,并且在视觉和代码格式方面都有很好的示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    • 2017-11-05
    • 2013-11-13
    相关资源
    最近更新 更多