

While there was an iterative and recursive traversal for linked lists, binary trees are much better suited for recursive traversal since each node can have two children. Non-empty binary tree The root IntTreeNode contains some data, a left subtree, and a right subtree. Empty binary tree The root IntTreeNode is null. A binary tree falls into one of the two categories. Like linked nodes, binary tree nodes as represented by IntTreeNode follow a recursive definition. In order to access items in the left half of the data structures, flip the direction of the edges and recursively apply this pattern to each sublist. Instead of entering from the beginning of the linked list, maintain a reference to the middle node. The critical optimization is to change the entry point so that it’s more convenient for binary search. This is much, much slower than an array! Goal Develop a data structure that balances fast search with fast insertion and fast removal. Unlike arrays, getting the middle element of a linked list is very slow since we need to iterate (or recurse) to the middle of the list.

Why is binary search in sorted a linked list so much slower than in a sorted array? Unfortunately, this doesn’t work well for binary search. When we ran into this problem with inserting or removing elements from the beginning of an arrays, we applied a new approach based on linked nodes. Inserting elements into a sorted array will take linear time since we’ll need to copy over all of the elements into a new, sorted array. Unfortunately, arrays are fixed in size, making it difficult to add new items to a sorted array-based set. In each iteration of the binary search algorithm, half of the elements under consideration can be discarded, resulting in a logarithmic time algorithm. In the worst case, the runtime of binary search tree operations are all in Θ(log 2 N) with respect to the N, the size of the binary search tree.īinary search trees are very closely related to the binary search algorithm that we introduced earlier for finding the index of a target element in a sorted array. In a binary search tree, elements are stored in sorted order. This week, we’ll be learning about the fundamental data structure behind Java’s TreeSet and TreeMap implementations: binary search trees (BSTs).
