您当然可以把一个把一幅图建模成一棵树。下面的代码将创建一个新的图,它包含了一棵有序的二叉树。有时像这样的图也被称为是连通无环图,因为在图中没有环。这就是说一旦您离开这个顶点,就没有其它的路径可以让您再回到这了。相对的,航线图是一个有环的图,因为有多种方式可以访问一个顶点。
You can of course model a tree structure as a graph. The following code will create a new graph
containing an ordered binary tree. A graph like this is sometimes referred to as a connected acyclic
graph as there are no cycles in the graph. This means that once you leave a node there is no other
path you could take that will allow you to get there again. By contrast the air routes graph is an
example of a cyclic graph as there are clearly many ways to revisit vertices.
我们可以使用max,min这些步骤找出图中最大最小的值。然而下面的查询说如了我们怎么用一个有序的二叉树来找出最大最小值。
We could of course use the max and the min steps to find the largest and smallest values in the
graph. However, the queries below show how we can do it using the semantics of an ordered
binary tree.
顺带提示:这是一种不同的方式:我们可以使用not来写查询而不用count.因为not在Groovy中是一个保留字,就像我们在“警告:保留字冲突”这一节中讨论的一样,我们可以用一个下划线的前缀。
As a side note, here is a different way we could have written the query using not instead of count.
As not is a reserved word in Groovy, as we discussed in the "A warning about reserved word
conflicts and collisions" section, we have to prefix it with the __. notation.
如果我们想要看到repeat步骤在遍历树的过程中遇到的值我们可以加一个emit步骤,这样就可以重到重复访问的顶点的值了。注意不包含根结点的值。
If we wanted to see the values that the repeat is encountering as it traverses the tree we could add
an emit step and get the values of each node the repeat visits. Note that this does not include the
value from the root node.
或许另一个更好的方式查看我们在遍历树过程中遇到的所有值,可以用一个path步骤像下面这样。注意这个也不包含根结点的值。
Perhaps a nicer way to look at all the values we encountered as we traversed the tree would be to
use path as follows. Note that this does include the root node’s value.
通过运行下面的查询,我们可以看到所有访问树的可能的路径
We can see all of the possible paths through the tree by running the following query.
在“把图转化为树”这一节中,我们快速地搜索了TinkerPop 树的API。我们将会用使在那讨论的技术从我们的二叉树图中创建一个树对象,像下面这样。
We briefly explored the TinkerPop Tree API in the "Turning graphs into trees" section. We could use
what we discussed there to create a Tree object from our Binary Tree graph as follows.
只是为了确认我们可以查询我们刚刚创建的是什么类型的对象。
Just to be sure we can query what kind of object we just created.
如果我们打印树,我们可以看到,如何从我们的原来的图把它创建出来。如果您学习了嵌套,您会看到,它确实代表了原来的二叉树的数据,它就是我们用来创建图的。
If we print the tree we can see how it has been created from our original graph. If you study the
nesting closely you will see that it does indeed represent the original binary tree data that we used
to create the graph.
我们可以用getObjectsAtDepth方法进一步的研究树的结构。
We can use the getObjectsAtDepth method to further investigate the tree structure.
浙公网安备 33010602011771号