1: public T add(T newEntry)
2: {
3: T result = null;
4:
5: if (isEmpty())
6: setRootNode(new BinaryNode<>(newEntry));
7: else
8: {
9: BinaryNode<T> rootNode = getRootNode();
10: result = addEntry(rootNode, newEntry);
11: setRootNode(rebalance(rootNode));
12: } // end if
13:
14: return result;
15: } // end add
16:
17: private T addEntry(BinaryNode<T> rootNode, T newEntry)
18: {
19: assert rootNode != null;
20: T result = null;
21: int comparison = newEntry.compareTo(rootNode.getData());
22:
23: if (comparison == 0)
24: {
25: result = rootNode.getData();
26: rootNode.setData(newEntry);
27: }
28: else if (comparison < 0)
29: {
30: if (rootNode.hasLeftChild())
31: {
32: BinaryNode<T> leftChild = rootNode.getLeftChild();
33: result = addEntry(leftChild, newEntry);
34: rootNode.setLeftChild(rebalance(leftChild));
35: }
36: else
37: rootNode.setLeftChild(new BinaryNode<>(newEntry));
38: }
39: else
40: {
41: assert comparison > 0;
42:
43: if (rootNode.hasRightChild())
44: {
45: BinaryNode<T> rightChild = rootNode.getRightChild();
46: result = addEntry(rightChild, newEntry);
47: rootNode.setRightChild(rebalance(rightChild));
48: }
49: else
50: rootNode.setRightChild(new BinaryNode<>(newEntry));
51: } // end if
52:
53: return result;
54: } // end addEntry
55: // Version 4.0
56: