llrb-stats.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Copyright 2010 Petar Maymounkov. 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. package llrb
  5. // GetHeight() returns an item in the tree with key @key, and it's height in the tree
  6. func (t *LLRB) GetHeight(key Item) (result Item, depth int) {
  7. return t.getHeight(t.root, key)
  8. }
  9. func (t *LLRB) getHeight(h *Node, item Item) (Item, int) {
  10. if h == nil {
  11. return nil, 0
  12. }
  13. if less(item, h.Item) {
  14. result, depth := t.getHeight(h.Left, item)
  15. return result, depth + 1
  16. }
  17. if less(h.Item, item) {
  18. result, depth := t.getHeight(h.Right, item)
  19. return result, depth + 1
  20. }
  21. return h.Item, 0
  22. }
  23. // HeightStats() returns the average and standard deviation of the height
  24. // of elements in the tree
  25. func (t *LLRB) HeightStats() (avg, stddev float64) {
  26. av := &avgVar{}
  27. heightStats(t.root, 0, av)
  28. return av.GetAvg(), av.GetStdDev()
  29. }
  30. func heightStats(h *Node, d int, av *avgVar) {
  31. if h == nil {
  32. return
  33. }
  34. av.Add(float64(d))
  35. if h.Left != nil {
  36. heightStats(h.Left, d+1, av)
  37. }
  38. if h.Right != nil {
  39. heightStats(h.Right, d+1, av)
  40. }
  41. }