github.com/searKing/golang/go@v1.2.117/container/traversal/preorder.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#Post-order_(LRN) 6 package traversal 7 8 // Pre-order (NLR) 9 // 1. Check if the current node is empty or null. 10 // 2. Display the data part of the root (or current node). 11 // 3. Traverse the left subtree by recursively calling the pre-order function. 12 // 4. Traverse the right subtree by recursively calling the pre-order function. 13 // Implement: 14 // postorder(node) 15 // if (node = null) 16 // return 17 // visit(node) 18 // postorder(node.left) 19 // postorder(node.right) 20 21 // TODO template in Go2.0 is expected 22 // Preorder traversals from node ele by Pre-order (NLR) 23 // ele is a node which may have some interfaces implemented: 24 // LeftNodes|MiddleNodes|RightNodes 25 func Preorder(node any, handler Handler) { 26 traversal(node, traversalerFunc(preorder), handler) 27 } 28 29 func preorder(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 root 39 if !handler.Handle(node) { 40 return false 41 } 42 // traversal children 43 if !preorder(node.middleLevelNodes(), handler) { 44 return false 45 } 46 if !preorder(node.leftLevelNodes(), handler) { 47 return false 48 } 49 if !preorder(node.rightLevelNodes(), handler) { 50 return false 51 } 52 } 53 return true 54 }