Binary Search Trees

advertisement
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
17
72
44
61
89
Left “child” is less than “parent”
51
23
17
72
44
61
89
51
Right “child” is >= than “parent”
23
17
72
44
61
89
51
23
17
72
44
61
89
This property is recursively true for both sides!
51
23
17
72
44
61
89
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 performance for:
– Searching
– Inserting new data
– Updating data
Logarithms
(specifically log2n)
How many times can
you chop it in half?
Logarithms
(specifically log2n)
16
Logarithms
(specifically log2n)
1 chop
16
8
8
Logarithms
(specifically log2n)
2 chops
16
8
4
8
4
4
4
Logarithms
(specifically log2n)
3 chops
16
8
8
4
2
4
2
2
4
2
2
4
2
2
2
Logarithms
(specifically log2n)
4 chops
16
8
8
4
4
2
1
2
1
1
2
1 1
4
2
4
2
1 1 11 1
2
1
2
1 1
2
1 1
1
Logarithms
(specifically log2n)
log216 = 4
16
8
8
4
4
2
1
2
1
1
2
1 1
4
2
4
2
1 1 11 1
2
1
2
1 1
2
1 1
1
Looking for the number 61
51
23
17
72
44
61
89
Is 61 >= 51?
51
23
17
72
44
61
89
Is 61 >= 51?
Yes! Go right!
51
23
17
72
44
61
89
Is 61 >= 51?
Yes! Go right!
51
23
17
72
44
61
89
Is 61 >= 72?
51
23
17
72
44
61
89
Is 61 >= 72?
No! Go left!
51
23
17
72
44
61
89
Is 61 >= 72?
No! Go left!
51
23
17
72
44
61
89
We have 7 nodes
log27 = 2(-ish)
51
23
17
72
44
61
89
What if we had 4G nodes?
51
23
17
72
44
61
89
What if we had 4G nodes?
51
4,000,000,000,000
23
17
72
44
61
89
log24G = 32
51
23
17
72
44
61
89
Where Performance Degrades
Where Performance Degrades
11
Where Performance Degrades
11
12
Where Performance Degrades
11
12
Where Performance Degrades
11
12
13
Where Performance Degrades
11
12
13
15
Where Performance Degrades
11
12
13
15
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
Download