/* * Tyler Mi * * A class representing a binary search tree of integers */ public class IntTree { private IntTreeNode overallRoot; // Constructs an empty tree public IntTree() { overallRoot = null; } // Adds the given value into the current tree, maintaining // the BST property public void add(int value) { overallRoot = add(value, overallRoot); } // Add in the given value into the tree represented by the // given root, maintaining the BST property private IntTreeNode add(int value, IntTreeNode root) { if (root == null) { root = new IntTreeNode(value); } else if (value < root.data) { root.left = add(value, root.left); } else if (value > root.data) { root.right = add(value, root.right); } return root; } // DO NOT DO THIS CODE OF "STOPPING ONE EARLY" // Trust in x=change(x)!! You can get to a null part // of the tree and still be fine! // Adds the given value into the current tree public void badAdd(int value) { if (overallRoot == null) { overallRoot = new IntTreeNode(value); } else { badAdd(value, overallRoot); } } // Adds the given value into the tree represented by the given root private void badAdd(int value, IntTreeNode root) { if (value < root.data) { if (root.left == null) { root.left = new IntTreeNode(value); } else { badAdd(value, root.left); } } else if (value > root.data) { if (root.right == null) { root.right = new IntTreeNode(value); } else { badAdd(value, root.right); } } } // Prints the preorder traversal of the current tree public void printPreorder() { System.out.print("preorder:"); printPreorder(overallRoot); System.out.println(); } // Prints the preorder traversal of the tree represented by the // given root of it private void printPreorder(IntTreeNode root) { if (root != null) { System.out.print(" " + root.data); printPreorder(root.left); printPreorder(root.right); } } // Returns whether or not a value is contained within the current // tree public boolean contains(int value) { 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(int value, IntTreeNode root) { if (root == null) { return false; } else if (root.data == value) { return true; } else if (value < root.data) { return contains(value, root.left); } else { return contains(value, root.right); } } /* * Class for storing a single node of a binary tree of ints */ 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; } } }