You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: book/content/part03/binary-search-tree.asc
+8-5
Original file line number
Diff line number
Diff line change
@@ -52,11 +52,14 @@ With the methods `add` and `remove`, we have to guarantee that our tree always h
52
52
===== Inserting new elements in a BST
53
53
54
54
.For inserting an element in a BST, we have two scenarios:
55
-
1. If the tree is empty (root element is null), we add the newly created node as root, and that's it!
56
-
2. If the root is not null. Start from it and compare the node’s value against the new element. If the node has higher than a new item, we move to the right child, otherwise to the left. We check each node recursively until we find an empty spot to put the new element and keep the rule `right < parent < left`.
57
-
3. If we insert the same value multiple times, we don’t want duplicates. So, we can keep track of multiples using a duplicity counter.
58
-
59
-
For instance, let’s say that we want to insert the values 19, 21, 10, 2, 8 in a BST:
55
+
. If the tree is empty (root element is null), we add the newly created node as root, and that's it!
56
+
. If the tree has a root, compare the new value with the root. Then we have three possibilities:
57
+
.. `root == newValue`: we increase the duplicity counter in that case, and done!
58
+
.. `root > newValue`, we search on the left side of the root.
59
+
.. `root < newValue`, we search on the right side of the root.
60
+
. Repeat the comparison between the current node and `newValue`, until we find the value or (null) space.
61
+
62
+
For instance, let’s say that we want to insert the values 19, 21, 10, 2, 18 in a BST:
0 commit comments