} // End function /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Function: insertNode * * Input: BinaryNode, Integer * * Output: BinaryNode * * Description: A function that compares the values of nodes with * * incoming values and determines if they are less * * than or greater than the current value and makes * * the appropriate connections. * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ public BinaryNode insertNode(BinaryNode root, int newValue) { // Check to see if root exists if (root == null) { return(root = new BinaryNode(newValue)); // Create new node } else if (root.getValue() < newValue) // Moves to the right { // Checks if right child exists if (root.getRightChild() == null) { // Set a new node to be the right child root.setRightChild(new BinaryNode(newValue)); numOfNodes++; // Keeps track of when new nodes are added } return(insertNode(root.rightChild, newValue)); } else if (root.getValue() > newValue) // Moves to the left { // Checks if left child exists if (root.getLeftChild() == null) { // Set a new node to be the left child root.setLeftChild(new BinaryNode(newValue)); numOfNodes++; // Keeps track of when new nodes are added } return(insertNode(root.leftChild, newValue)); } return(root); } // End function
} // End function /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Function: inorderTrav * * Input: BinaryNode * * Output: void * * Description: A recursive function that traverses a binary tree * * inorder, and displays the results to the user. * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ public static void inorderTrav(BinaryNode root) { // Check to see if the tree is empty if (root == null) { return; } inorderTrav(root.getLeftChild()); // Traverse left Console.Write(root.getValue() + " "); // Print node value inorderTrav(root.getRightChild()); // Traverse right } // End function