Does anyone know how to figure out search time for a binary search tree(i.e. worst-case, best-case, and average-case)?
相关问题
- binary search tree path list
- Stop child process when parent process stops
- Yield all root-to-leaf branches of a Binary Tree
- Pygame Distribution - Runtime Error
- Class in jar not found at runtime, but was used to
相关文章
- Is there an existing solution for these particular
- Defining preprocessor symbols for CLion analyzer
- How to create new type at runtime in F#? [closed]
- How can I create a MetadataWorkspace using metadat
- JNI or Runtime.exec()?
- Create a java class dynamically and compile and in
- Client-side Development Platforms based on JavaScr
- Recursively change system property at runtime in j
For a non-self-balancing tree (possible but unusual for a search tree), worst case is O(n), which is for the degenerate binary tree (a linked list).
In this case, you have to search, on average, half the list before finding your desired element.
Best case is O(log2 n) for a perfectly balanced tree, since you cut the search space in half for every tree level.
Average case is somewhere in between those two and depends entirely on the data :-)
Since you rarely get to control the sequence in which data is inserted into a tree, self-balancing trees are usually preferable since, while they add a small amount of time to each insertion or deletion, they greatly speed up searching. Their worst case is so much better than unbalanced trees.
In this perfectly balanced tree, you can see that you get 2n-1 nodes for every
n
levels. That means for 15 nodes, you never have to search more than four nodes to find it (e.g., to find13
, you search8
,12
,14
and13
). That's where the log2n figure comes from.A degenerate unbalanced tree, as already stated, is a linked list. If your data arrived in sequence and you inserted it into an unbalanced binary tree, you'd get:
To find
13
in that case, you'd need to search1
,2
,3
,4
,5
,6
,7
,8
,9
,10
,11
,12
and13
, hence O(n).Best case is O(1). the first element could be the item you are looking for. worst case is O(n) ie in a skewed tree and average case is O(lg n).
Might want to tag this one as "homework". Here's a good starting point: http://en.wikipedia.org/wiki/Binary_search_tree
In general, a balanced binary search tree has a worst-case lookup of O(log n), best case of O(1) (when the desired value is the root) and an average case of O(log n) (the leaves contain exponentially more values than their parents).
The worst case is the most interesting and is easily seen by recognizing that the first level of a binary tree has 1 node, the second has 2, the third has 4 and so on. Thus, the number of nodes in a binary tree of depth n is precisely 2^n - 1. The mathematical inverse of the exponential function is the logarithm, thus: O(log n).
An unbalanced tree can be as bad as a linked list and may have a shape like the following:
In this situation, the worst-case access time is O(n).