node.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. //@File node.go
  2. //@Time 2022/05/12
  3. //@Author #Suyghur,
  4. package rbtree
  5. type Color bool
  6. const (
  7. RED = false
  8. BLACK = true
  9. )
  10. type Node struct {
  11. parent *Node
  12. left *Node
  13. right *Node
  14. color Color
  15. key interface{}
  16. value interface{}
  17. }
  18. func (node *Node) Key() interface{} {
  19. return node.key
  20. }
  21. func (node *Node) Value() interface{} {
  22. return node.value
  23. }
  24. func (node *Node) SetValue(value interface{}) {
  25. node.value = value
  26. }
  27. func (node *Node) Next() *Node {
  28. return successor(node)
  29. }
  30. func (node *Node) Prev() *Node {
  31. return preSuccessor(node)
  32. }
  33. // successor returns the successor of the Node
  34. func successor(node *Node) *Node {
  35. if node.right != nil {
  36. return minimum(node.right)
  37. }
  38. y := node.parent
  39. for y != nil && node == y.right {
  40. node = y
  41. y = node.parent
  42. }
  43. return y
  44. }
  45. // preSuccessor returns the preSuccessor of the Node
  46. func preSuccessor(node *Node) *Node {
  47. if node.left != nil {
  48. return maximum(node.left)
  49. }
  50. if node.parent != nil {
  51. if node.parent.right == node {
  52. return node.parent
  53. }
  54. for node.parent != nil && node.parent.left == node {
  55. node = node.parent
  56. }
  57. return node.parent
  58. }
  59. return nil
  60. }
  61. // minimum finds the minimum Node of subtree n.
  62. func minimum(node *Node) *Node {
  63. for node.left != nil {
  64. node = node.left
  65. }
  66. return node
  67. }
  68. // maximum finds the maximum Node of subtree n.
  69. func maximum(node *Node) *Node {
  70. for node.right != nil {
  71. node = node.right
  72. }
  73. return node
  74. }