Question

Binary Search Tree Code in Java Write a program that prompts user to enter however many...

Binary Search Tree Code in Java

Write a program that prompts user to enter however many numbers they want to add to the binary search tree. Then have the user input numbers until the tree contains that many elements. If the user enters a number that already exists in the tree, then a message should be displayed "Number is already in the tree". Once all elements are added to the tree print its contents in sorted order.

Assume all user input is valid.

Homework Answers

Answer #1

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

//BinarySearchTree.java

import java.util.Scanner;

public class BinarySearchTree {

      // attributes for storing the root node and size

      private Node root;

      private int size;

      // constructor

      public BinarySearchTree() {

            root = null;

            size = 0;

      }

      // method to add a number to the tree, returns true if added successfully,

      // false if number already exists.

      public boolean add(int data) {

            // if root is null, adding as root node, otherwise calling recursive

            // helper method to add

            if (root == null) {

                  root = new Node(data);

                  size++;

                  return true;

            } else {

                  return add(data, root);

            }

      }

      // recursive helper method to add a number, after finding proper position

      private boolean add(int data, Node node) {

            // if node's data is same as data, returning false (duplicate)

            if (node.data == data) {

                  return false;

            }

            // if data is smaller than node's data, moving to left subtree,

            // otherwise moving to right subtree

            else if (data < node.data) {

                  // if left subtree is null, adding as left node

                  if (node.left == null) {

                        node.left = new Node(data);

                        size++;

                        return true;

                  } else {

                        // otherwise moving to left node recursively and adding at

                        // proper position

                        return add(data, node.left);

                  }

            } else {

                  // if right subtree is null, adding as right node

                  if (node.right == null) {

                        node.right = new Node(data);

                        size++;

                        return true;

                  } else {

                        // otherwise moving to right node recursively and adding at

                        // proper position

                        return add(data, node.right);

                  }

            }

      }

      // method to print elements in order (sorted)

      public void inorderTraversal() {

            // calling recursive helper method, passing root

            inorderTraversal(root);

      }

      // recursive helper method to print elements in order

      private void inorderTraversal(Node node) {

            // if node is null, exiting from method (base case)

            if (node == null) {

                  return;

            }

            // performing in order traversal on left tree

            inorderTraversal(node.left);

            // printing / visiting current node's data

            System.out.print(node.data + " ");

            // performing in order traversal on right tree

            inorderTraversal(node.right);

      }

      // returns the size

      public int getSize() {

            return size;

      }

      /**

      * main method to interact with the user

      */

      public static void main(String[] args) {

            Scanner scanner = new Scanner(System.in);

            // creating a binary search tree

            BinarySearchTree tree = new BinarySearchTree();

            System.out.print("How many numbers do you want to add? ");

            // reading tree size

            int n = scanner.nextInt();

            // loops until tree's size becomes n

            while (tree.getSize() < n) {

                  // asking for a number, reading it, adding to tree

                  System.out.print("Enter number #" + (tree.getSize() + 1) + ": ");

                  int num = scanner.nextInt();

                  if (!tree.add(num)) {

                        // if addition returned false, displaying error

                        System.out.println("Number is already in the tree");

                  }

            }

            // displaying elements in sorted order

            System.out.println("Tree in sorted order: ");

            tree.inorderTraversal();

      }

}

// simple Node class to represent a single node. should be placed in same file

class Node {

      int data;

      Node left, right;

      public Node(int data) {

            this.data = data;

      }

}

/*OUTPUT*/

How many numbers do you want to add? 10

Enter number #1: 23

Enter number #2: 19

Enter number #3: 0

Enter number #4: 45

Enter number #5: 33

Enter number #6: 12

Enter number #7: 23

Number is already in the tree

Enter number #7: 0

Number is already in the tree

Enter number #7: 70

Enter number #8: 2

Enter number #9: -2

Enter number #10: 4

Tree in sorted order:

-2 0 2 4 12 19 23 33 45 70

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Write a program that prompts the user to enter an integer number between 1 and 999....
Write a program that prompts the user to enter an integer number between 1 and 999. The program displays the sum of all digits in the integer if the input is valid; otherwise, it displays a message indicating that the integer is not between 1 and 999 and hence, is invalid. Name the program file Q1.cpp Example: if the user enters 12, sum of digits is 3. If the user enters 122, sum of digits is 5.
IN JAVA: Write code (using ArrayLists) to read a line of input from the user and...
IN JAVA: Write code (using ArrayLists) to read a line of input from the user and print the words of that line in sorted order, without removing duplicates. For example, the program output might look like the following: Type a message to sort: to be or not to be that is the question Your message sorted: be be is not or question that the to to
design a program that prompts the user to enter a positive integer number and reads the...
design a program that prompts the user to enter a positive integer number and reads the user’s input. If the user input is not a positive number, the program should prompt them repeatedly until they enter a valid input. Once a valid input is received ,the program uses a loop to calculate the sum of the digits of the user’s input and displays the sum. For example, if the user enters the number 94311, the program should print the sum...
In this lab, you will write a program that creates a binary search tree based on...
In this lab, you will write a program that creates a binary search tree based on user input. Then, the user will indicate what order to print the values in. **Please write in C code** Start with the bst.h and bst.c base code provided to you. You will need to modify the source and header file to complete this lab. bst.h: #ifndef BST_H #define BST_H typedef struct BSTNode { int value; struct BSTNode* left; struct BSTNode* right; } BSTNode; BSTNode*...
Write a program to allow user to create a binary search tree. Your program should display...
Write a program to allow user to create a binary search tree. Your program should display in BFT and DFT(in order) format.
PLease code a C++ program that prompts a user to enter 10 numbers. this program should...
PLease code a C++ program that prompts a user to enter 10 numbers. this program should read the numbers into an array and find the smallest number in the list, the largest numbers in the list the sum of the 10 numbers and the average of the 10 numbers please use file i/o and input measures for Handling Errors in C++ When Opening a File
Create a Python program that: Allows the user to enter a phrase or sentence. The program...
Create a Python program that: Allows the user to enter a phrase or sentence. The program should then take the phrase or sentence entered Separate out the individual words entered Each individual word should then be added to a list After all of the words have been place in a list Sort the contents of the list Display the contents of the sorted list with each individual word displayed on a separate line Display a message to the user indicating...
Write a program that asks the user to enter a series of numbers separated by commas....
Write a program that asks the user to enter a series of numbers separated by commas. Here is an example of valid input: 7,9,10,2,18,6 The program should calculate and print the sum of all the numbers. Sample Run java NumberSum Enter·numbers·separated·by·commas:1,2,3↵ 6↵
Write a java program that creates an integer array with 50 random values, prompts the user...
Write a java program that creates an integer array with 50 random values, prompts the user to enter the index of an element in the array between 0 and 49, then displays the corresponding element value. If the specified index is out of bounds, display an error message (e.g. “Out of Bounds”) and ask the user to enter another index. Use a while loop that will keep prompting the user until a valid input is received. To handle invalid inputs,...
Write a complete C++ program asking the user to enter numbers one by one. User enters...
Write a complete C++ program asking the user to enter numbers one by one. User enters only whole numbers 0 and 10. Once the user enters 0, then the program should print sum of only odd numbers entered by user prior to 0. A valid scenario given below: Enter a number: 5 Enter a number: 3 Enter a number: 2 Enter a number: 3 Enter a number: 8 Enter a number: 0 Sum of the odd numbers you entered is...