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