/* * Kyle Pierce * CSE 143 * * This class represents a generic binary search tree */ public class SearchTree> { private TreeNode overallRoot; // post: constructs an empty tree public SearchTree() { overallRoot = null; } // pre: tree is a binary search tree // post: value added to overall tree to preserve // binary search tree property public void add(E value) { overallRoot = add(overallRoot, value); } // pre: tree is a binary search tree // post: value added to tree with given root to preserve // binary search tree property public TreeNode add(TreeNode root, E value) { if (root == null) { root = new TreeNode(value); } else if (value.compareTo(root.data) < 0) { root.left = add(root.left, value); } else if (value.compareTo(root.data) > 0) { root.right = add(root.right, value); } return root; } // pre: tree is a binary search tree // post: returns true if the given value is in the tree, false otherwise public boolean contains(E value) { return contains(overallRoot, value); } // pre: tree is a binary search tree // post: returns true if the given value is in given tree, false otherwise private boolean contains(TreeNode root, E value) { if (root == null) { return false; } else if (root.data.equals(value)) { return true; } else if (root.data.compareTo(value) < 0) { return contains(root.left, value); } else { return contains(root.right, value); } } // post: returns a String representation of the tree public String toString() { String s = toString(overallRoot); return "[" + s.substring(0, s.length() - 2) + "]"; } // post: returns a String representation of the given tree private String toString(TreeNode root) { if (root == null) { return ""; } else { return toString(root.left) + root.data + ", " + toString(root.right); } } }