Basic Usage

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/container/gtree"
  5. "github.com/gogf/gf/v2/util/gutil"
  6. )
  7. func main() {
  8. m := gtree.NewRedBlackTree(gutil.ComparatorInt)
  9. // Set key-value pairs
  10. for i := 0; i < 10; i++ {
  11. m.Set(i, i*10)
  12. }
  13. // Query size
  14. fmt.Println(m.Size())
  15. // Batch set key-value pairs (different data type objects have different parameters)
  16. m.Sets(map[interface{}]interface{}{
  17. 10: 10,
  18. 11: 11,
  19. })
  20. fmt.Println(m.Size())
  21. // Check existence
  22. fmt.Println(m.Contains(1))
  23. // Query key-value
  24. fmt.Println(m.Get(1))
  25. // Remove item
  26. m.Remove(9)
  27. fmt.Println(m.Size())
  28. // Batch remove
  29. m.Removes([]interface{}{10, 11})
  30. fmt.Println(m.Size())
  31. // Current list of keys (random order)
  32. fmt.Println(m.Keys())
  33. // Current list of values (random order)
  34. fmt.Println(m.Values())
  35. // Query key, if key does not exist, write the given default value
  36. fmt.Println(m.GetOrSet(100, 100))
  37. // Remove key-value pair and return the corresponding value
  38. fmt.Println(m.Remove(100))
  39. // Iterate over map
  40. m.IteratorAsc(func(k interface{}, v interface{}) bool {
  41. fmt.Printf("%v:%v ", k, v)
  42. return true
  43. })
  44. fmt.Println()
  45. // Clear map
  46. m.Clear()
  47. // Check if map is empty
  48. fmt.Println(m.IsEmpty())
  49. }

After execution, the output is:

  1. 12
  2. true
  3. 10
  4. 11
  5. 9
  6. [0 1 2 3 4 5 6 7 8]
  7. [0 10 20 30 40 50 60 70 80]
  8. 100
  9. 100
  10. 0:0 1:10 2:20 3:30 4:40 5:50 6:60 7:70 8:80
  11. true

Pre-order/Post-order Traversal

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/container/gtree"
  5. "github.com/gogf/gf/v2/util/gutil"
  6. )
  7. func main() {
  8. tree := gtree.NewAVLTree(gutil.ComparatorInt)
  9. for i := 0; i < 10; i++ {
  10. tree.Set(i, i*10)
  11. }
  12. // Print tree
  13. tree.Print()
  14. // Pre-order traversal
  15. fmt.Println("ASC:")
  16. tree.IteratorAsc(func(key, value interface{}) bool {
  17. fmt.Println(key, value)
  18. return true
  19. })
  20. // Post-order traversal
  21. fmt.Println("DESC:")
  22. tree.IteratorDesc(func(key, value interface{}) bool {
  23. fmt.Println(key, value)
  24. return true
  25. })
  26. }

After execution, the output is:

  1. ┌── 9
  2. ┌── 8
  3. ┌── 7
  4. ┌── 6
  5. └── 5
  6. └── 4
  7. └── 3
  8. ┌── 2
  9. └── 1
  10. └── 0
  11. ASC:
  12. 0 0
  13. 1 10
  14. 2 20
  15. 3 30
  16. 4 40
  17. 5 50
  18. 6 60
  19. 7 70
  20. 8 80
  21. 9 90
  22. DESC:
  23. 9 90
  24. 8 80
  25. 7 70
  26. 6 60
  27. 5 50
  28. 4 40
  29. 3 30
  30. 2 20
  31. 1 10
  32. 0 0