如何在R中为给定数量的分支和深度构建N-ary树,例如深度为3的二叉树?
编辑:将来源问题与问题和答案分开。
答案 0 :(得分:2)
我想提出解决方案,我用它来构建具有 leafAmn 分支因子的树数据结构。要在树中存储数据,请使用字段 myData 。还定义了打印树的内容的功能。此外,它还存在此任务的递归解决方案: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
答案 1 :(得分:1)
好吧,很久以前,当Q-BASIC没有任何指针选项时,有一种方法可以表示没有指针的二叉树。这是一个简单的数学技巧。当您为root分配1时,它有两个子项 - 2,3。 “2”有两个子节点“4,5”,可以表示为“索引* 2”和“索引* 2 + 1”。因此,我们可以用数组表示二叉树。这是我的代码。
let x = a.filter { !b.contains($0) }