This is a creation in Article, where the information may have evolved or changed.
About what is a two-fork search tree, unclear classmates can go to see me write this data structure and algorithm of the website
Data
First we define the data structures that are needed. Note that the left and right nodes of the TreeNode are *treenode type, and the tree has only one root data field, which is *treenode type
type TreeNode struct { Value int Left *TreeNode Right *TreeNode}type BinarySearchTree struct { Root *TreeNode}
Insert
To insert an element into a binary search tree, first locate the inserted position, and then insert it. Note here that our implementation method adds a method to the two type TreeNode and Binarysearchtree. You need to be aware of how to add methods to the type, and also note that if you want to change the method caller, you need to use pointers
func (tree BinarySearchTree) Insert (v int) { tree.Root.Insert(v)}func (node *TreeNode) Insert (v int){ if v < node.Value { if node.Left != nil{ node.Left.Insert(v) }else{ node.Left = &TreeNode{v, nil, nil} } }else { if node.Right != nil{ node.Right.Insert(v) }else{ node.Right = &TreeNode{v, nil, nil} } }}
Traverse
The traversal of a tree has a pre-order, a sequence, a middle order, etc. Here, take the middle order as an example. Note the difference between the slice and the slice pointer
func (tree BinarySearchTree) InOrder() []int{ var res []int tree.Root.InOrder(&res) return res}func (node *TreeNode) InOrder(result *[]int) { if node.Left != nil{ node.Left.InOrder(result) } *result = append(*result, node.Value) if node.Right != nil{ node.Right.InOrder(result) }}
Maximum minimum value
func (tree BinarySearchTree) FindMin() int { node := tree.Root for { if node.Left != nil { node = node.Left }else{ return node.Value } }}func (tree BinarySearchTree) FindMax() int { node := tree.Root for { if node.Right != nil { node = node.Right }else{ return node.Value } }}
Find
func (tree BinarySearchTree) Contains(v int) bool { node := tree.Root for { if node == nil{ return false }else if (node.Value == v) { return true }else if (node.Value > v){ node = node.Left }else{ node = node.Right } }}