Efficiency of in Binary Trees Computer Science 4 Reference: Objective: Understand efficiency of Binary Trees
Efficiency of adding an item Searches down through the tree until it finds where to place the item. Only one probe per level of the tree So runtime is proportional to the depth of the tree. Turns out that the average depth of a binary tree with N elements is Log2N However, worst case depth is N (e.g. when items have been entered in alphabetical order.) Therefore adding to a binary tree is O(LogN) average case but O(N) worst case.
Efficiency of Finding or Deleting an item Finding an item never makes more than one probe per level. O(LogN) average case O(N) worst case Deleting an item involves finding the item to delete, then looking for the item to replace it with. Both are O(LogN) average case and O(N) worst case. Therefore deleting is O(LogN) average case, O(N) worst case.
Efficiency of Binary Search Tree Operations Unsorted List Sorted List BST (Average) BST (Worst) Add O(1) O(N) O(LogN) Find Delete
Balanced Binary Trees Algorithms exist to “balance” binary trees The trees they build always have O(LogN) levels. Therefore all their operations are O(LogN) Accessible via the TreeMap and TreeSet classes
TreeSets/TreeMaps Recall that Java provides Set and Map interfaces. Java provides a balanced binary tree algorithm to implement these interfaces. These are call TreeMaps and TreeSets.
Operations on Set ADT void clear() - Empty the set. boolean add(object obj) - Add to the set, returns whether it is a new item boolean contains(object obj) - In the set? boolean isEmpty() - Nothing in the set? boolean remove(object obj) - Remove from the set. Returns true if it was in the set. int size() - Number of items in the set. Iterator iterator() - Iterate over all set members
Operations on Map ADT clear, isEmpty, and size operations as in set. Object put(Object key, Object value) - Add key/value mapping. Return previous value mapped to key or null if none. Object get(Object key) - Return value key maps to. Object remove(Object key) - Remove object from map. Return mapped value (or null if none). boolean containsKey(Object key) - Key in map? Iterator?
Summary Binary Trees add, delete, and find items in O(LogN) time average case O(N) time worst case Average case is an improvement on sorted and unsorted lists. Worst case is not. Algorithms exist to balance trees so their worst case on all operations is O(LogN) Java allows access to these algorithms via the TreeMap and TreeSet classes