Java Reference
In-Depth Information
A clever reader might notice that this method violates the principle of Boolean
Zen that we introduced in Chapter 5. This method can be written more concisely as a
boolean
expression. For example, it can be written as a single expression as follows:
private boolean contains(IntTreeNode root, int value) {
return root != null && (root.data == value ||
(value < root.data && contains(root.left, value)) ||
contains(root.right, value));
}
In this case, it is debatable whether the single expression is more readable than the
if/else
version of the code. This is somewhat a matter of personal taste, so different
programmers will prefer one version over the other, but our conclusion was that the
longer version is actually easier to read in this case.
Here is the complete implementation of the
IntSearchTree
class:
1 // This class stores int values in a binary search tree.
2 // Duplicates are allowed. Each node of the tree has the binary
3 // search tree property.
4
5
public class
IntSearchTree {
6
private
IntTreeNode overallRoot;
7
8 // post: constructs an empty tree
9
public
IntSearchTree() {
10 overallRoot = null;
11 }
12
13 // post: value is added to overall tree so as to preserve the
14 // binary search tree property
15
public void
add(
int
value) {
16 overallRoot = add(overallRoot, value);
17 }
18
19 // post: value is added to given tree so as to preserve the
20 // binary search tree property
21
private
IntTreeNode add(IntTreeNode root,
int
value) {
22
if
(root == null) {
23 root =
new
IntTreeNode(value);
24 }
else if
(value <= root.data) {
25 root.left = add(root.left, value);
26 }
else
{
27 root.right = add(root.right, value);
28 }
Search WWH ::
Custom Search