1// SPDX-License-Identifier: ISC 2// Copyright (c) 2014-2020 Bitmark Inc. 3// Use of this source code is governed by an ISC 4// license that can be found in the LICENSE file. 5 6package avl 7 8import ( 9 "fmt" 10) 11 12// to control the print routine 13type branch int 14 15const ( 16 root branch = iota 17 left branch = iota 18 right branch = iota 19) 20 21// Print - display an ASCII graphic representation of the tree 22func (tree *Tree) Print(printData bool) int { 23 return printTree(tree.root, "", root, printData) 24} 25 26// internal print - returns the maximum depth of the tree 27func printTree(tree *Node, prefix string, br branch, printData bool) int { 28 if nil == tree { 29 return 0 30 } 31 rd := 0 32 ld := 0 33 if nil != tree.right { 34 t := " " 35 if left == br { 36 t = "| " 37 } 38 rd = printTree(tree.right, prefix+t, right, printData) 39 } 40 switch br { 41 case root: 42 fmt.Printf("%s|------+ ", prefix) 43 case left: 44 fmt.Printf("%s\\------+ ", prefix) 45 case right: 46 fmt.Printf("%s/------+ ", prefix) 47 } 48 up := interface{}(nil) 49 if nil != tree.up { 50 up = tree.up.key 51 } 52 if printData { 53 fmt.Printf("%q → %q ^%v %+2d/[%d,%d]\n", tree.key, tree.value, up, tree.balance, tree.leftNodes, tree.rightNodes) 54 } else { 55 fmt.Printf("%q ^%v\n", tree.key, up) 56 } 57 if nil != tree.left { 58 t := " " 59 if right == br { 60 t = "| " 61 } 62 ld = printTree(tree.left, prefix+t, left, printData) 63 } 64 if rd > ld { 65 return 1 + rd 66 } else { 67 return 1 + ld 68 } 69} 70