|
| 1 | +# Binary Search Tree |
| 2 | + |
| 3 | +Insert and search for numbers in a binary tree. |
| 4 | + |
| 5 | +When we need to represent sorted data, an array does not make a good |
| 6 | +data structure. |
| 7 | + |
| 8 | +Say we have the array `[1, 3, 4, 5]`, and we add 2 to it so it becomes |
| 9 | +`[1, 3, 4, 5, 2]` now we must sort the entire array again! We can |
| 10 | +improve on this by realizing that we only need to make space for the new |
| 11 | +item `[1, nil, 3, 4, 5]`, and then adding the item in the space we |
| 12 | +added. But this still requires us to shift many elements down by one. |
| 13 | + |
| 14 | +Binary Search Trees, however, can operate on sorted data much more |
| 15 | +efficiently. |
| 16 | + |
| 17 | +A binary search tree consists of a series of connected nodes. Each node |
| 18 | +contains a piece of data (e.g. the number 3), a variable named `left`, |
| 19 | +and a variable named `right`. The `left` and `right` variables point at |
| 20 | +`nil`, or other nodes. Since these other nodes in turn have other nodes |
| 21 | +beneath them, we say that the left and right variables are pointing at |
| 22 | +subtrees. All data in the left subtree is less than or equal to the |
| 23 | +current node's data, and all data in the right subtree is greater than |
| 24 | +the current node's data. |
| 25 | + |
| 26 | +For example, if we had a node containing the data 4, and we added the |
| 27 | +data 2, our tree would look like this: |
| 28 | + |
| 29 | + 4 |
| 30 | + / |
| 31 | + 2 |
| 32 | + |
| 33 | +If we then added 6, it would look like this: |
| 34 | + |
| 35 | + 4 |
| 36 | + / \ |
| 37 | + 2 6 |
| 38 | + |
| 39 | +If we then added 3, it would look like this |
| 40 | + |
| 41 | + 4 |
| 42 | + / \ |
| 43 | + 2 6 |
| 44 | + \ |
| 45 | + 3 |
| 46 | + |
| 47 | +And if we then added 1, 5, and 7, it would look like this |
| 48 | + |
| 49 | + 4 |
| 50 | + / \ |
| 51 | + / \ |
| 52 | + 2 6 |
| 53 | + / \ / \ |
| 54 | + 1 3 5 7 |
| 55 | + |
| 56 | + |
| 57 | +## Submitting Exercises |
| 58 | + |
| 59 | +Note that, when trying to submit an exercise, make sure the solution is in the `exercism/python/<exerciseName>` directory. |
| 60 | + |
| 61 | +For example, if you're submitting `bob.py` for the Bob exercise, the submit command would be something like `exercism submit <path_to_exercism_dir>/python/bob/bob.py`. |
| 62 | + |
| 63 | +For more detailed information about running tests, code style and linting, |
| 64 | +please see the [help page](http://exercism.io/languages/python). |
| 65 | + |
| 66 | +## Source |
| 67 | + |
| 68 | +Wikipedia [https://en.wikipedia.org/wiki/Binary_search_tree](https://en.wikipedia.org/wiki/Binary_search_tree) |
| 69 | + |
| 70 | +## Submitting Incomplete Solutions |
| 71 | +It's possible to submit an incomplete solution so you can see how others have completed the exercise. |
0 commit comments