前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Groovy中 前序和后序树遍历

Groovy中 前序和后序树遍历

作者头像
白石
发布2019-08-23 10:00:44
5860
发布2019-08-23 10:00:44
举报
文章被收录于专栏:白石白石

前序和后序树遍历

Groovy中的Node类有depthFirstbreadthFirst方法,可以使用深度优先遍历或广度优先遍历返回Node对象的集合。由于Groovy 2.5.0,我们可以指定是使用preorder(默认值)还是postorder遍历。此外,这些方法现在接受一个“闭包”,该“闭包”将为每个访问的节点调用。Closure将当前“节点”作为第一个参数,第二个参数是当前节点的树级。

在下面的例子中,我们读取了一些XML,然后使用depthFirst以几种方式访问节点树:

代码语言:javascript
复制
// We start with a XML node hierarchy.
def xml = '''
        <A>
          <B>
            <D/>
            <E/>
          </B>
          <C>
            <F/>
          </C>
        </A>
        '''
def root = new XmlParser().parseText(xml)
 
// Preorder traversal is default, but
// we can also specify it with the boolean
// argument of depthFirst method.
assert root.depthFirst(true)
           .collect { node -> node.name() } == ['A', 'B', 'D', 'E', 'C', 'F']
            
// Groovy 2.5.0 adds possibility to
// directly call closure for
// each node visited where the first
// Closure argument is the node and
// the second argument the level.
def result = []
root.depthFirst { node, level -> result << "$level${node.name()}" }
 
assert result == ['1A', '2B', '3D', '3E', '2C', '3F']
 
// Postorder traversal can be specified
// by setting preorder argment to false.
// When used in combination with Closure
// argument we must using named argument
// preorder.
result = []
root.depthFirst(preorder: false) { node -> result << node.name() }
 
assert result == ['D', 'E', 'B', 'F', 'C', 'A']

在第二个示例中,我们使用了breadthFirst方法。这意味着树中每层访问的节点:

代码语言:javascript
复制
// Let's create a Node hierarchy.
def builder = NodeBuilder.newInstance()
def root = builder.A {
    B {
        D()
        E()
    }
    C {
        F()
    }
}
 
 
// Preorder traversal is default, but
// we can also specify it with the boolean
// argument of breadthFirst method.
assert root.breadthFirst(true)
           .collect { node -> node.name() } == ['A', 'B', 'C', 'D', 'E', 'F']
            
// Groovy 2.5.0 adds possibility to
// directly call closure for
// each node visited with node and level.
def result = []
root.breadthFirst { node, level -> result << "$level${node.name()}" }
 
assert result == ['1A', '2B', '2C', '3D', '3E', '3F']
 
// Postorder traversal is implemented
// as starting at the lowest level and
// working our way up.
result = []
root.breadthFirst(preorder: false) { node -> result << node.name() }
 
assert result == ['D', 'E', 'F', 'B', 'C', 'A']

用Groovy 2.5.0编写。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前序和后序树遍历
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档