370 likes | 463 Vues
Binary Search Trees (aka BSTs). Just another data structure Dynamic Non-linear Left pointer Right pointer Still have access only to the headNode Is amazingly fast**!. ** When balanced. 51. 23. 72. 89. 61. 44. 17. 51. 23. 72. 89. 61. 44. 17.
E N D
Binary Search Trees(aka BSTs) • Just another data structure • Dynamic • Non-linear • Left pointer • Right pointer • Still have access only to the headNode • Is amazingly fast**! ** When balanced
51 23 72 89 61 44 17
51 23 72 89 61 44 17 Left “child” is less than “parent”
51 23 72 89 61 44 17 Right “child” is >= than “parent”
51 23 72 89 61 44 17 This property is recursively true for both sides!
51 23 72 89 61 44 17 This property is recursively true for both sides!
Why is this SO AMAZING? • Searching • If value of data < this node, go left • If value of data >= this node, go right • Each pass cuts the data in half! • Logarithmic performancefor: • Searching • Inserting new data • Updating data
Logarithms(specifically log2n) How many times can you chop it in half?
Logarithms(specifically log2n) 1 chop 16 1 chop 8 8
Logarithms(specifically log2n) 2 chops 16 1 chop 8 8 1 chop 4 4 4 4
Logarithms(specifically log2n) 3 chops 16 1 chop 8 8 1 chop 4 4 4 4 1 chop 2 2 2 2 2 2 2 2
Logarithms(specifically log2n) 4 chops 16 1 chop 8 8 1 chop 4 4 4 4 1 chop 2 2 2 2 2 2 2 2 1 chop 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Logarithms(specifically log2n) log216 = 4 16 1 chop 8 8 1 chop 4 4 4 4 1 chop 2 2 2 2 2 2 2 2 1 chop 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
51 23 72 89 61 44 17 Looking for the number 61
51 23 72 89 61 44 17 Is 61 >= 51?
51 23 72 89 61 44 17 Is 61 >= 51? Yes! Go right!
51 23 72 89 61 44 17 Is 61 >= 51? Yes! Go right!
51 23 72 89 61 44 17 Is 61 >= 72?
51 23 72 89 61 44 17 Is 61 >= 72? No! Go left!
51 23 72 89 61 44 17 Is 61 >= 72? No! Go left!
51 23 72 89 61 44 17 We have 7 nodes log27 = 2(-ish)
51 23 72 89 61 44 17 What if we had 4G nodes?
51 23 72 89 61 44 17 What if we had 4G nodes? 4,000,000,000,000
51 23 72 89 61 44 17 log24G = 32
Where Performance Degrades 11 12 13
Where Performance Degrades 11 12 13 15
Where Performance Degrades 11 12 13 15 Linked List
Code class LL_Node { int data; Node next;}
BST Code class LL_Node { int data; Node next;} class BST_Node { int data; Node left; Node right;}
BST Code public void traverse () { if (left != null) { left.traverse(); } Console.WriteLine(this.data); if (right != null) { right.traverse(); } }
BST Code public void traverse () { if (left != null) { left.traverse(); } Console.WriteLine(this.data); if (right != null) { right.traverse(); } } Trace this. It’s worth it!
Summary • YADS (yet another data structure) • Dynamic • Non-linear • Left pointer • Right pointer • Still have access only to the headNode • Is amazingly fast**! ** When balanced