将树结构实现为 R 中的列表

implement tree structure as list in R

我正在尝试将这个简单的树结构实现为 R 中的列表:

  1
 / \
2  3
  / \
 4  5

我试过的是这样的:

tree <- list(1, list(2, 3, list(4, 5)))

> tree
[[1]]
[1] 1

[[2]]
[[2]][[1]]
[1] 2

[[2]][[2]]
[1] 3

[[2]][[3]]
[[2]][[3]][[1]]
[1] 4

[[2]][[3]][[2]]
[1] 5

这是正确的吗?根据我的理解,这棵树看起来像这样:

   1
 / \ \
2  3  .
     / \
     4  5

更新 :

我也试过这个:

tree <- list(1, list(2, c(3, list(4, 5))))

但它看起来也不对

树只需要节点名称。

tree <- list(data=1, 
             lchild=list(data=2), 
             rchild=list(data=3, 
                         lchild=list(data=4), 
                         rchild=list(data=5)))

考虑 data.tree 包。它很好地打印了嵌套列表的结构:

tree <- list("1" = 1, 
             "2" = list(2), 
             "3" = list(3, "4" = list(4), "5" = list(5)))

data.tree::FromListSimple(tree, nodeName = "1")

Returns:

  levelName
1 1        
2  ¦--2    
3  °--3    
4      ¦--4
5      °--5