github.com/Nigel2392/go-datastructures@v1.1.5/binarytree/bst_node.go (about) 1 package binarytree 2 3 import "github.com/Nigel2392/go-datastructures" 4 5 type BSTNode[T datastructures.Ordered] struct { 6 value T 7 left *BSTNode[T] 8 right *BSTNode[T] 9 } 10 11 func (n *BSTNode[T]) Value() T { 12 return n.value 13 } 14 15 func (n *BSTNode[T]) insert(v T) (inserted bool) { 16 if n.value < v { 17 if n.right == nil { 18 n.right = &BSTNode[T]{value: v} 19 return true 20 } else { 21 return n.right.insert(v) 22 } 23 } else if n.value > v { 24 if n.left == nil { 25 n.left = &BSTNode[T]{value: v} 26 return true 27 } else { 28 return n.left.insert(v) 29 } 30 } 31 return false 32 } 33 34 func (n *BSTNode[T]) search(value T) (v T, ok bool) { 35 // if we've reached the end of the tree, the value is not present 36 if n == nil { 37 return 38 } 39 40 // check if we need to traverse further down the tree 41 if n.value < value { 42 return n.right.search(value) 43 } else if n.value > value { 44 return n.left.search(value) 45 } 46 47 // value is not less than or greater than, so it must be equal 48 return n.value, true 49 } 50 51 func (n *BSTNode[T]) delete(v T) (newRoot *BSTNode[T], deleted bool) { 52 if n == nil { 53 return nil, false 54 } 55 56 if v < n.value { 57 n.left, deleted = n.left.delete(v) 58 } else if v > n.value { 59 n.right, deleted = n.right.delete(v) 60 } else { 61 deleted = true 62 if n.left == nil { 63 return n.right, deleted 64 } else if n.right == nil { 65 return n.left, deleted 66 } 67 68 minRight := n.right.findMin() 69 minRight.right, _ = n.right.delete(minRight.value) 70 minRight.left = n.left 71 return minRight, deleted 72 } 73 74 return n, deleted 75 } 76 77 func (n *BSTNode[T]) findMin() *BSTNode[T] { 78 current := n 79 for current.left != nil { 80 current = current.left 81 } 82 return current 83 } 84 85 func (n *BSTNode[T]) getHeight() int { 86 if n == nil { 87 return 0 88 } 89 90 leftHeight := n.left.getHeight() 91 rightHeight := n.right.getHeight() 92 93 if leftHeight > rightHeight { 94 return leftHeight + 1 95 } 96 97 return rightHeight + 1 98 } 99 100 func (n *BSTNode[T]) traverse(f func(T)) { 101 if n == nil { 102 return 103 } 104 105 n.left.traverse(f) 106 f(n.value) 107 n.right.traverse(f) 108 } 109 110 func (n *BSTNode[T]) deleteIf(predicate func(T) bool) (newRoot *BSTNode[T], deleted int) { 111 if n == nil { 112 return nil, 0 113 } 114 115 n.left, deleted = n.left.deleteIf(predicate) 116 n.right, deleted = n.right.deleteIf(predicate) 117 118 if predicate(n.value) { 119 deleted++ 120 if n.left == nil { 121 return n.right, deleted 122 } else if n.right == nil { 123 return n.left, deleted 124 } 125 126 minRight := n.right.findMin() 127 minRight.right, _ = n.right.delete(minRight.value) 128 minRight.left = n.left 129 return minRight, deleted 130 } 131 132 return n, deleted 133 }