// This class represents a binary search tree of integers public class IntSearchTree { private IntTreeNode overallRoot; // Constructs an empty binary search tree. public IntSearchTree() { overallRoot = null; } // Adds the given value to the binary search tree public void add(int value) { overallRoot = add(overallRoot, value); } // Adds the value to the subtree with the given root private IntTreeNode add(IntTreeNode root, int value) { if (root == null) { root = new IntTreeNode(value); } else if (value < root.data) { // go left // add the value to the left subtree root.left = add(root.left, value); } else { // value >= root.data // go right root.right = add(root.right, value); } return root; } /**** Don't do this or I'll cry :'( ****/ private void addNoXEqualsChangeX(IntTreeNode root, int value) { // this doesn't even work if overallRoot is null, // need to add a special case in the public method too :'( if (root.left == null && root.right == null) { if (value < root.data) { root.left = new IntTreeNode(value); } else if (value > root.data) { root.right = new IntTreeNode(value); } } else if (value < root.data) { if (root.left == null) { root.left = new IntTreeNode(value); } else { add(root.left, value); } } else if (value > root.data) { if (root.right == null) { root.right = new IntTreeNode(value); } else { add(root.right, value); } } } // Prints the numbers in this tree in a in-order fashion. public void printInorder() { System.out.print("inorder:"); printInorder(overallRoot); System.out.println(); } // Prints the numbers of the subtree rooted at root // using a in-order traversal. private void printInorder(IntTreeNode root) { if (root != null) { printInorder(root.left); System.out.print(" " + root.data); printInorder(root.right); } } // Class that represents a single node in the tree private static class IntTreeNode { public int data; public IntTreeNode left; public IntTreeNode right; // Constructs a leaf node with given data public IntTreeNode(int data) { this(data, null, null); } // Constructs a branch node with given data, left subtree, right subtree public IntTreeNode(int data, IntTreeNode left, IntTreeNode right) { this.data = data; this.left = left; this.right = right; } } }