/* * Tyler Mi * * A class representing a tree of integers */ public class IntTree { private IntTreeNode overallRoot; // Constructs an empty tree public IntTree() { overallRoot = null; } // 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) { // The empty tree holds no values, so the value can't be // in this tree return false; } else { // A value is in this tree if it matches the data of the // root, or is in either of the subtrees return root.data == value || contains(value, root.left) || 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; } } }