Example. Inserting into a binary search tree

[comp1110-2W]

Here BST is our example of a binary search tree type:

BST insert(BST tree, int element) { if(tree == null) { return new BST(element, null, null); } if(tree.value <= element) { tree.right = insert(tree.right, element); return tree; } else { tree.left = insert(tree.left, element); return tree; } }

The above code (almost) always modifies an existing tree. A more "functional" version that always creates a new (slightly modified) copy of the original tree would look as follows:

BST insert(BST tree, int element) { if(tree == null) { return new BST(element, null, null); } if(tree.value <= element) { BST newRight = insert(tree.right, element); return new BST(tree.value, tree.left, newRight); } else { BST newLeft = insert(tree.left, element); return new BST(tree.value, newLeft, tree.right); } }

Either version of the function ensures that the Data Invariant on the BST Definition is preserved.

bars magnifying-glass caret-down plus minus arrow-right xmark