/* * Tyler Mi * * A class representing a binary search tree of comparable * objects */ public class SearchTree> { private TreeNode overallRoot; // Constructs an empty tree public SearchTree() { overallRoot = null; } // Adds the given value into the current tree, maintaining // the BST property public void add(E value) { overallRoot = add(value, overallRoot); } // Add in the given value ino the tree represented by the // given root, maintaining the BST property private TreeNode add(E value, TreeNode root) { if (root == null) { root = new TreeNode(value); } else if (value.compareTo(root.data) < 0) { root.left = add(value, root.left); } else if (value.compareTo(root.data) > 0) { root.right = add(value, root.right); } return root; } // Returns whether or not a value is contained within the current // tree public boolean contains(E value) { if (value == null) { throw new IllegalArgumentException(); } return contains(value, overallRoot); } // Returns whether or not a value is contained within the // tree represented by the given root of it private boolean contains(E value, TreeNode root) { if (root == null) { return false; } else if (value.equals(root.data)) { return true; } else if (value.compareTo(root.data) < 0) { return contains(value, root.left); } else { return contains(value, root.right); } } // Returns an inorder traversal of the current search tree // surrounded in brackets, with each element separated by commas public String toString() { String traversal = getInorder(overallRoot); return "[" + traversal.substring(0, traversal.length() - 2) + "]"; } // Returns an inorder traversal of the search tree represented // by the given root, surrounded in brackets, with each element // separated by commas private String getInorder(TreeNode root) { if (root == null) { return ""; } else { return getInorder(root.left) + root.data + ", " + getInorder(root.right); } } /* * Class for storing a single node of a binary tree of Es */ private static class TreeNode { public E data; public TreeNode left; public TreeNode right; // constructs a leaf node with given data public TreeNode(E data) { this(data, null, null); } // constructs a branch node with given data, left subtree, // right subtree public TreeNode(E data, TreeNode left, TreeNode right) { this.data = data; this.left = left; this.right = right; } } }