Question

Programming Project #5 – Binary Tree

Exercise 19 on page 637 of the text a through f

Here is the array to build the initial binary tree:
int [] data = { 50, 30, 60, 10, 80, 55, 40 };

BUT, make sure the code works with any binary tree created from an array named data

In addition to the main .java file, make sure you also create a Node.java and a Tree.java file that contain the code that allows you to build a linked list style binary tree.

Here are some test cases, be sure the above array is the default tree when you turn it in.
int [] data = { 80, 70, 60, 50, 90, 40, 30, 20, 10 };
int [] data = { 50, 30, 60, 10, 80, 55, 40, 85, 75, 65, 55, 95, 45, 35, 25, 15 };

Please have 3 .java files. (Main.java, Node.java, Tree.java). All separated.

Thank you! :)

Picture of page 637 for Exercise 19 is attached below:

19 Given the recursive nature of a binary tree, a good strategy for writing a Java method that operates on a binary tree is o

0 0
Add a comment Improve this question Transcribed image text
Answer #1

1 class BinaryTreeNode { /** <terminated > BinaryTree Example [Java A 1 3 6 7 9 15 Height: 3 * Stores the integer of this nod

// Node.java
class Node {
    /**
     * 
     * Stores the integer of this node
     * 
     */
    private int data;
    /**
     * 
     * Reference to the left Tree
     * 
     */
    private Node left;
    /**
     * 
     * Reference to the right Tree
     * 
     */
    private Node right;

    /**
     * 
     * Default Constructor
     * 
     */
    public Node() {
        left = null;
        right = null;
        data = 0;
    }

    /**
     * 
     * Constructor which specifies the data to be stored
     * 
     * @param data
     * 
     */
    public Node(int data) {
        left = null;
        right = null;
        this.data = data;
    }

    /**
     * 
     * Returns the data stored in this node
     * 
     * @return Data member variable
     * 
     */
    public int getData() {
        return data;
    }

    /**
     * 
     * Returns the left Binary Tree
     * 
     * @return Left binary tree
     * 
     */
    public Node getLeft() {
        return left;
    }

    /**
     * 
     * Returns the right Binary Tree
     * 
     * @return Right binary tree
     * 
     */
    public Node getRight() {
        return right;
    }

    /**
     * 
     * Inserts a node into either the left or right tree where appropriate
     * 
     * @param newData Reference to the new data
     * 
     */
    public void insert(int newData) {
        if (newData < data) {
            if (left == null)
                left = new Node(newData);
            else
                left.insert(newData);
        } else if (newData > data) {
            if (right == null)
                right = new Node(newData);
            else
                right.insert(newData);
        } else
            System.out.println("Duplicate - not adding " + newData);
    }

    public int height() {
        if (left == null && right == null) {
            return 1;
        }
        int l = 0;
        if (left != null) {
            l = left.height();
        }
        int r = 0;
        if (right != null) {
            r = right.height();
        }
        return 1 + Math.max(l, r);
    }
    
    public int count() {
        if (left == null && right == null) {
            return 1;
        }
        int l = 0;
        if (left != null) {
            l = left.count();
        }
        int r = 0;
        if (right != null) {
            r = right.count();
        }
        return 1 + l + r;
    }
}

// Tree.java
class Tree {
    /**
     * 
     * Reference to the root Node of the tree
     * 
     */
    Node root = null;

    /**
     * 
     * Insert the data into the tree
     * 
     * @param newData New int to store in the tree
     * 
     */
    public void insertInTree(int newData) {
        if (root == null)
            root = new Node(newData);
        else
            root.insert(newData);
    }

    /**
     * 
     * Method to display the contents of the tree
     * 
     */
    public void displayInOrder() {
        displayInOrder(root);
    }

    /**
     * 
     * Traverse the tree using InOrder traversal and display the content to the
     * console
     * 
     * @param subRoot The node to start with
     * 
     */
    private void displayInOrder(Node subRoot) {
        if (subRoot == null)
            return;
        displayInOrder(subRoot.getLeft());
        System.out.print(" " + subRoot.getData() + " ");
        displayInOrder(subRoot.getRight());
    }

    public int getHeight() {
        return root.height();
    }

    
    public int maxValue() {
        return maxValue(root);
    }
    
    public int maxValue(Node start) {
        int max = start.getData();

        if(start.getLeft() != null) {
            int x = maxValue(start.getLeft());
            if(x > max) {
                max = x;
            }
        }
        if(start.getRight() != null) {
            int x = maxValue(start.getRight());
            if(x > max) {
                max = x;
            }
        }
        
        return max;
    }

    public int numNodes() {
        return root.count();
    }

    public int treeSum() {
        return treeSum(root);
    }

    private int treeSum(Node subRoot) {
        int value = subRoot.getData();
        if(subRoot.getLeft() != null) {
            value += treeSum(subRoot.getLeft());
        }
        if(subRoot.getRight() != null) {
            value += treeSum(subRoot.getRight());
        }
        return value;
    }
    public double avg() {
        return treeSum() / (double) numNodes();
    }

    public boolean searchValue(int search) {
        return searchValue(root, search);
    }

    private boolean searchValue(Node subRoot, int search) {
        if (subRoot.getData() == search) {
            return true;
        }
        if (subRoot.getLeft() != null && searchValue(subRoot.getLeft(), search)) {
            return true;
        }
        if (subRoot.getRight() != null && searchValue(subRoot.getRight(), search)) {
            return true;
        }
        return false;
    }

}

// Main.java
public class Main {
    public static void main(String[] args) {
        Tree tree = new Tree();
        tree.insertInTree(6);
        tree.insertInTree(3);
        tree.insertInTree(9);
        tree.insertInTree(1);
        tree.insertInTree(15);
        tree.insertInTree(7);
        tree.displayInOrder();
        System.out.println();
        System.out.println("Height: " + tree.getHeight());
        
        System.out.println(tree.numNodes());
        System.out.println(tree.maxValue());
        System.out.println(tree.treeSum());
        System.out.println(tree.avg());
        System.out.println(tree.searchValue(40));
    }
}

please upvote. Thanks!

Add a comment
Know the answer?
Add Answer to:
Programming Project #5 – Binary Tree Exercise 19 on page 637 of the text a through...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Binary Search Tree Part A: The code attached in this document is a sample code to demonstrate ins...

    Binary Search Tree Part A: The code attached in this document is a sample code to demonstrate insert operation in binary search tree. Please fill in the missing part for the insert method to make the program work. The expected output should be as follows. 20 30 40 50 60 70 80 Part B: Find Lowest Common Ancestor (LCA) of a Binary Search Tree. According to WikiPedia definition , The lowest common ancestor is defined between two nodes v and...

  • Consider the class specifications for the Binary Tree class and Binary Search Tree class in the...

    Consider the class specifications for the Binary Tree class and Binary Search Tree class in the attached files // BinaryTree.h #include <iostream> using namespace std; //Definition of the Node template <class elemType> struct TreeNode { elemType data; TreeNode<elemType> *left; TreeNode<elemType> *right; }; //Definition of class Binary Tree template <class elemType> class BinaryTree { protected: TreeNode<elemType> *root; public: BinaryTree(); BinaryTreel const BinaryTree<elemType>& otherTree); BinaryTree(); bool is Empty() const; virtual boot search(const elemType& searchItem) const = 0; virtual void insert(const elemType& insertItem)...

  • Binary Tree Template Write your own version of a class template that will create a binary...

    Binary Tree Template Write your own version of a class template that will create a binary tree that can hold values of any data type. Demonstrate the class with a driver program. Place your binary tree template in it's own header file, Btree.h. Include methods for the following: inserting new values into the tree removing nodes from the tree searching the tree returning the number of nodes in the tree displaying the contents of the tree using preorder traversal Your...

  • Trees Traversals Please write a Java program to traverse a binary tree in in-order and pre-order,...

    Trees Traversals Please write a Java program to traverse a binary tree in in-order and pre-order, and to plot a binary tree into a 2-dimensional array. You may write many recursive methods for this project. You are not allowed to use any existing Java classes such as ArrayList or Vector or Tree. Please stop your program if the user enters 0 as the tree selection. Your program must run the following Test Case 1 plus two more test cases to...

  • Trees Traversals Please write a Java program to traverse a binary tree in in-order and pre-order, and to plot a binar...

    Trees Traversals Please write a Java program to traverse a binary tree in in-order and pre-order, and to plot a binary tree into a 2-dimensional array. You may write many recursive methods for this project. You are not allowed to use any existing Java classes such as ArrayList or Vector or Tree. Please stop your program if the user enters 0 as the tree selection. Your program must run the following Test Case 1 plus two more test cases to...

  • Write a function, swapSubtrees, that swaps all of the left and right subtrees of a binary...

    Write a function, swapSubtrees, that swaps all of the left and right subtrees of a binary tree. Add this function to the class binaryTreeType and create a program to test this function. #include <iostream> using namespace std; //Definition of the Node template <class elemType> struct nodeType { elemType info; nodeType<elemType> *lLink; nodeType<elemType> *rLink; }; //Definition of the class template <class elemType> class binaryTreeType { public: //Overload the assignment operator. const binaryTreeType<elemType>& operator=(const binaryTreeType<elemType>&) { if (this != &otherTree) //avoid self-copy...

  • Suppose a binary tree data (in tiny written size) is stored in an array (A) as...

    Suppose a binary tree data (in tiny written size) is stored in an array (A) as given below and root is placed at “0”index. Note the array indices are in larger written size (0 to 74). Show the traversal data of the given tree for a)      In-Order Traversal b)     Post Order Traversal A 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 28 13 36 15 9 22 44 7 10 75 33 19 15...

  • IN JAVA 2 A Binary Search Tree The goal of this lab is to gain familiarity...

    IN JAVA 2 A Binary Search Tree The goal of this lab is to gain familiarity with simple binary search trees. 1. Begin this lab by implementing a simple class that represents a "node” in a binary search tree, as follows. public class MyTreeNode<t extends Comparable<T>> { public T data; public MyTreeNode<T> leftchild; public MyTreeNode<T> rightChild; public MyTreeNode<T> parent; 2. Have the second member of your pair type in the code for the simple binary search tree interface. public interface...

  • 1) Extend the Binary Search Tree ADT to include a public method leafCount that returns the...

    1) Extend the Binary Search Tree ADT to include a public method leafCount that returns the number of leaf nodes in the tree. 2) Extend the Binary Search Tree ADT to include a public method singleParent-Count that returns the number of nodes in the tree that have only one child. 3) The Binary search tree ADT is extended to include a boolean method similarTrees that receives references to two binary trees and determines whether the shapes of the trees are...

  • 1. Write a function in Tree class which returns true if and only if the tree...

    1. Write a function in Tree class which returns true if and only if the tree satisfies the binary search tree property. The function’s header line is public boolean isValidBST() And in the attached code, you just need to finish the function after the comment: “//Instructor hint: please write your code here:” Make sure you execute your code, and the result in the main function after calling your function should be same as the prompt message I write. Clearly you...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT