1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
| package main
import "fmt"
type BNode struct { data int64 left *BNode right *BNode }
type BTree interface { Insert(data int64) Delete(data int64) Find(data interface{}) *BNode }
type Tree struct { root *BNode }
func (t *Tree) Insert(data int64) *Tree { node := &BNode{data: data} if t.root == nil { t.root = node return t } current := t.root for { if data < current.data { if current.left == nil { current.left = node break } current = current.left } if data > current.data { if current.right == nil { current.right = node break } current = current.right } } return t }
func (t *Tree) Delete(data int64) bool { if t.root == nil { return false } var parent *BNode current := t.root for { if data == current.data { if current.left == nil && current.right == nil { if parent == nil { t.root = nil return true } if parent.left == current { parent.left = nil } else { parent.right = nil } return true } if current.left != nil && current.right == nil { if parent == nil { parent = current.left return true } if parent.left == current { parent.left = current.left } else { parent.right = current.left } } if current.left == nil && current.right != nil { if parent == nil { parent = current.right return true } if parent.left == current { parent.left = current.right } else { parent.right = current.right } } if current.left != nil && current.right != nil { minNode := current.right minNodeParent := current for minNode.left != nil { minNodeParent = minNode minNode = minNode.left } current.data = minNode.data if current.right == minNode { current.right = minNode.right } else { minNodeParent.left = minNode.right } return true } } else if data < current.data { if current.left == nil { return false } parent = current current = current.left } else if data > current.data { if current.right == nil { return false } parent = current current = current.right } }
}
func (t *Tree) Find(value int64) *BNode { if t.root == nil { return nil } current := t.root for { if value == current.data { break } if value < current.data { current = current.left } if value > current.data { current = current.right } } return current }
|