Reputation: 3640
I'm trying to implement this simple tree structure as a list in R:
1
/ \
2 3
/ \
4 5
What I tried is this:
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
Is this correct? From my understanding this tree looks like this:
1
/ \ \
2 3 .
/ \
4 5
update :
I also tried this:
tree <- list(1, list(2, c(3, list(4, 5))))
but it looks wrong, too
Upvotes: 0
Views: 784
Reputation: 331
The Tree just needs the node name.
tree <- list(data=1,
lchild=list(data=2),
rchild=list(data=3,
lchild=list(data=4),
rchild=list(data=5)))
Upvotes: 1
Reputation: 4768
Consider the data.tree
package. It prints the structure of nested lists nicely:
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
Upvotes: 1