github.com/searKing/golang/go@v1.2.117/container/traversal/outorder.go (about) 1 // Copyright 2020 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // https://en.wikipedia.org/wiki/Tree_traversal#Out-order_(RNL) 6 package traversal 7 8 // Out-order (RNL) 9 // 1. Check if the current node is empty or null. 10 // 2. Traverse the right subtree by recursively calling the out-order function. 11 // 3. Display the data part of the root (or current node). 12 // 4. Traverse the left subtree by recursively calling the out-order function. 13 // Implement: 14 // outorder(node) 15 // if (node = null) 16 // return 17 // outorder(node.right) 18 // visit(node) 19 // outorder(node.left) 20 21 // TODO template in Go2.0 is expected 22 // Outorder traversals from node ele by Out-order (RNL) 23 // ele is a node which may have some interfaces implemented: 24 // LeftNodes|MiddleNodes|RightNodes 25 func Outorder(node any, handler Handler) { 26 traversal(node, traversalerFunc(outorder), handler) 27 } 28 29 func outorder(currents []levelNode, handler levelNodeHandler) (goon bool) { 30 if len(currents) == 0 { 31 return true 32 } 33 // Step 1: brothers 34 for _, node := range currents { 35 if node.visited { 36 continue 37 } 38 // process children 39 if !outorder(node.rightLevelNodes(), handler) { 40 return false 41 } 42 43 // process root 44 if !handler.Handle(node) { 45 return false 46 } 47 // process children 48 if !outorder(node.middleLevelNodes(), handler) { 49 return false 50 } 51 if !outorder(node.leftLevelNodes(), handler) { 52 return false 53 } 54 } 55 return true 56 }