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