binary search trees Flashcards
(18 cards)
What is a data structure?
- Collection of data items manipulated by an algorithm or program
- Data item is an instance of a data type
- In java, data types include:
○ Primitive (int/char)
○ Built-in (string)
○ Compound (class)
What is an operation?
- Data structures are interfaced though operations
○ Basic set: add, search, delete, iterate
○ Ordered set: min, max, rank
○ Stack: pop/push
○ Queue: first/last
what are some operations that you can do to data?
add, search, remove, min/max
What is the add, search, remove, min/max of an array?
Big O
N N N N
What is the add, search, remove, min/max of a sorted array?
N
log N
N
1 (constant)
What is the add, search, remove, min/max of a linked list?
1
N
N
N
What is the add, search, remove, min/max of a sorted linked list?
N
N
N
1
What is a BST?
Binary Search Tree
Like sorted arrays, but also fast (logarithmic add delete)
Rooted binary tree satisfies search tree properties
What are the search tree properties?
- has single distinguished root node
- has an orientation downwards/outwards
- nodes ponted by a node X in outward direction from root are the children of X
- node pointed by X towards root are the parents
- each node has AT MOST 2 children (binary)
What is the height of a BST?
(aka depth)
a rooted tree is the length of the longest path from root to leaf
( count down the edges between nodes for each “level” of a bst)
What is the height of an empty BST?
0
What is a complete RBT?
all levels of the tree except the last one (they are uniform)
What is the minimal height of a RBT?
the height of a complete (non-empty) BST
How are items sorted in a BST?
- for each node X in tree:
all data in left subtree are SMALLER values than data item X
all data in right subtree are GREATER values than data item X
How to search for items in a BST?
- Traverse key recursively starting at root
- Base case:
- If current node is NULL, return false
- If k = key at current node, return true
- Recursive case:
- If k < key at current node, traverse left
- If k > key at current node, traverse right
- If k < key at current node, traverse left
How to add to bst?
- compare each traversal to the item to be added
- if less then, go left
- if more than, go right
- add to bst in lowest position
What is the efficiency of the balanced bst?
add = O(log N)
search = O(log N)
min/max = O(log N)
remove = O(log N)
How to delete from a bst?
- locate node you want to delete using search algorithm
- if node has no children (leaf) then: delete the node directly from tree
if node has 1 child:
- splice out node to remove
- replace with child node
if node has 2 children:
- replace n with its predecessor to preserve search tree property
-original is deleted from tree and new node points to other remaining child.