Groovy中 前序和后序树遍历

前序和后序树遍历

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

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

// 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方法。这意味着树中每层访问的节点:

// 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编写。

转载于:https://my.oschina.net/wstone/blog/3094458

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值