Advertisement
wavec022

bintree notes 2 and pattern matching

Mar 2nd, 2020
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. Binary Search Tree--
  2. Left side is strictly less than node; right strictly greater
  3. All leaves must also be binary search trees
  4.  
  5. Pattern matching-- the match thing; see the bintree file in notes
  6.  
  7. case class Bst(left: Bst[Int], item: Int, right: Bst[Int])
  8. this is a way to make one where you can do shit like
  9. tree.item
  10.  
  11. instead of using pattern matching
  12.  
  13. ==========
  14.  
  15. red black tree (balanced binary search tree)
  16.  
  17. this is a bst where every node is colored red or black
  18. criteria for binary search tree still apply
  19.  
  20. THE RULES (VERY IMPORTANT):
  21. Red Rule: Every red node has a black parent.
  22. Black Rule: Every path from root to bottom has the same number of black nodes.
  23.  
  24. If it's missing one or both children it's considered a bottom node.
  25.  
  26. It is the colors that enforce the balance
  27. - Balanced to within factor of 2-- shortest path 3 longest path 6 for example
  28. - shortest path black black black, longest black red black red black red etc (so it's x2)
  29.  
  30. Enough to guarantee height is O(logN)
  31.  
  32. ===
  33.  
  34. Searching is easy-- ignore colors and search like normal BST
  35.  
  36. Insert-- starts out easy; insert like ordinary BST and color the node red
  37. - Always color the node red
  38.  
  39. but what if inserting it fails the red rule?
  40. If you have a red node with a red parent, take the red node and the black grandparent and rearrange / recolor as red parent, two black children-- the rearranging is such that the "middle" node is the parent so that you can fulfill the proper format of parent, less than, greater than
  41.  
  42. Rebalancing practice
  43.  
  44. You can rebalance more than once
  45. how the heckity heck do you do this in code though
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement