gitee.com/quant1x/gox@v1.21.2/util/examples/btree/btree.go (about)

     1  // Copyright (c) 2015, Emir Pasic. 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  package main
     6  
     7  import (
     8  	"fmt"
     9  	"gitee.com/quant1x/gox/util/btree"
    10  )
    11  
    12  // BTreeExample to demonstrate basic usage of BTree
    13  func main() {
    14  	tree := btree.NewWithIntComparator(3) // empty (keys are of type int)
    15  
    16  	tree.Put(1, "x") // 1->x
    17  	tree.Put(2, "b") // 1->x, 2->b (in order)
    18  	tree.Put(1, "a") // 1->a, 2->b (in order, replacement)
    19  	tree.Put(3, "c") // 1->a, 2->b, 3->c (in order)
    20  	tree.Put(4, "d") // 1->a, 2->b, 3->c, 4->d (in order)
    21  	tree.Put(5, "e") // 1->a, 2->b, 3->c, 4->d, 5->e (in order)
    22  	tree.Put(6, "f") // 1->a, 2->b, 3->c, 4->d, 5->e, 6->f (in order)
    23  	tree.Put(7, "g") // 1->a, 2->b, 3->c, 4->d, 5->e, 6->f, 7->g (in order)
    24  
    25  	fmt.Println(tree)
    26  	// BTree
    27  	//         1
    28  	//     2
    29  	//         3
    30  	// 4
    31  	//         5
    32  	//     6
    33  	//         7
    34  
    35  	_ = tree.Values() // []interface {}{"a", "b", "c", "d", "e", "f", "g"} (in order)
    36  	_ = tree.Keys()   // []interface {}{1, 2, 3, 4, 5, 6, 7} (in order)
    37  
    38  	tree.Remove(2) // 1->a, 3->c, 4->d, 5->e, 6->f (in order)
    39  	fmt.Println(tree)
    40  	// BTree
    41  	//     1
    42  	//     3
    43  	// 4
    44  	//     5
    45  	//     6
    46  
    47  	tree.Clear() // empty
    48  	tree.Empty() // true
    49  	tree.Size()  // 0
    50  
    51  	// Other:
    52  	tree.Height()     // gets the height of the tree
    53  	tree.Left()       // gets the left-most (min) node
    54  	tree.LeftKey()    // get the left-most (min) node's key
    55  	tree.LeftValue()  // get the left-most (min) node's value
    56  	tree.Right()      // get the right-most (max) node
    57  	tree.RightKey()   // get the right-most (max) node's key
    58  	tree.RightValue() // get the right-most (max) node's value
    59  }