gpt4 book ai didi

r - 在 R 中构建 N 叉树

转载 作者:行者123 更新时间:2023-12-01 02:02:57 29 4
gpt4 key购买 nike

如何在 R 中为给定数量的分支和深度构建 N 叉树,例如深度为 3 的二叉树?

编辑:将源问题与问答分开。

最佳答案

我想提出解决方案,我用它来构建树数据结构 叶安姆 分支因子。要将数据存储在树中,字段 我的数据 用来。还定义了打印树内容的函数。它还存在此任务的递归解决方案:R Tree With n Branches .

# function to build N-ary tree
makeTree <- function(depth, leafAmn)
{
## leafAmn - branching factor
## depth - depth of tree
library(data.tree)

myTree <- Node$new("root", myData = c(-1)) # root node
for (i in 1:depth) # loop by tree depth
{
if (i == 1)
# create a set of nodes with depth 1
{
chldArr1 <- matrix("", 1, leafAmn)
for (j in 1:leafAmn)
{
# create children nodes
myTree$AddChild(j, myData = c())
# save links to children nodes to array 'chldArr1'
# this array is used to generate tree without using recursion
chldArr1[j] <- sprintf("myTree$children[[%d]]$", j)
}
}
else
# add childs at level 'i' to nodes at level 'i-1' using
# method AddChild
{
chldArr2 <- matrix("", 1, (leafAmn ^ i))
k <- 1
for (j in 1:(leafAmn ^ (i - 1)))
{
for (m in 1:leafAmn)
{
# create string which contains a command to execute
# this command is used to add child to nodes at previous level
commStr <- paste(chldArr1[j], sprintf("AddChild(%d, myData = c())", m), sep = "")
eval(parse(text = commStr))
print(commStr)
# save command to array 'chldArr2'
chldArr2[k] <- paste(chldArr1[j], sprintf("children[[%d]]$", m), sep = "")
k <- k + 1
}
}
chldArr1 <- chldArr2
}
}

## Make a tree with depth of '3' and 2 branches from each node
myTree <- makeTree(3, 2)
print(myTree, "myData")

> myTree <- makeTree(3, 2)
[1] "myTree$children[[1]]$AddChild(1, myData = c())"
[1] "myTree$children[[1]]$AddChild(2, myData = c())"
[1] "myTree$children[[2]]$AddChild(1, myData = c())"
[1] "myTree$children[[2]]$AddChild(2, myData = c())"
[1] "myTree$children[[1]]$children[[1]]$AddChild(1, myData = c())"
[1] "myTree$children[[1]]$children[[1]]$AddChild(2, myData = c())"
[1] "myTree$children[[1]]$children[[2]]$AddChild(1, myData = c())"
[1] "myTree$children[[1]]$children[[2]]$AddChild(2, myData = c())"
[1] "myTree$children[[2]]$children[[1]]$AddChild(1, myData = c())"
[1] "myTree$children[[2]]$children[[1]]$AddChild(2, myData = c())"
[1] "myTree$children[[2]]$children[[2]]$AddChild(1, myData = c())"
[1] "myTree$children[[2]]$children[[2]]$AddChild(2, myData = c())"
> print(myTree, "myData")
levelName myData
1 root -1
2 ¦--1 NA
3 ¦ ¦--1 NA
4 ¦ ¦ ¦--1 NA
5 ¦ ¦ °--2 NA
6 ¦ °--2 NA
7 ¦ ¦--1 NA
8 ¦ °--2 NA
9 °--2 NA
10 ¦--1 NA
11 ¦ ¦--1 NA
12 ¦ °--2 NA
13 °--2 NA
14 ¦--1 NA
15 °--2 NA

关于r - 在 R 中构建 N 叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34705412/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com