我在R中使用diagrammeR
库来创建和呈现二叉树。我发现它使用起来非常简单,它可以创建高质量的渲染。但是,创建一个不完全(完美)的树会产生混乱的渲染。
这是我的树有16片叶子(h = 4
)时得到的结果:
Fully binary tree
要清楚,每个节点标签都是节点data.frame的行名,表示传递给图表的节点序列:
nodes$label = rownames(nodes)
如果我从节点[31]添加一个节点[32],可以手动或通过add_node()
和add_edge()
函数获取以下内容:
Non-perfect binary tree
正如你所看到的,一切都变得混乱。我想直接在节点[31]下面有节点[32],边缘是直线。这个图书馆甚至可以吗?我无法弄清楚节点data.frame中节点的正确顺序。
以下是我的完整代码的样子:
library(DiagrammeR)
from = c(1, 1, 2, 2, 3, 3, 4, 4, 7, 7, 10, 10, 11, 11, 14, 14, 17, 17, 18, 18, 19, 19, 22, 22, 25, 25, 26, 26, 29, 29)
to = c(2, 17, 3, 10, 4, 7, 5, 6, 8, 9, 11, 14, 12, 13, 15, 16, 18, 25, 19, 22, 20, 21, 23, 24, 26, 29, 27, 28, 30, 31)
h=4
n = 2^(h+1)-1
edges = data.frame(from, to)
nodes = data.frame(id = 1:n, label=1:n, shape='circle')
g1 = create_graph(nodes, edges)
render_graph(g1, layout='tree', title='g1')
# add node [32] and edge [31-32]
edges2 = rbind(edges, c(31, 32))
nodes2 = nodes
nodes2[32, 1:2] = 32
nodes2[32, 3] = 'circle'
g2 = create_graph(nodes2, edges2)
render_graph(g2, layout='tree', title='g2')