Question

package hw3; import java.util.LinkedList; /* *********************************************************************** * A simple BST with int keys and no values...

package hw3;

import java.util.LinkedList;

/* ***********************************************************************
* A simple BST with int keys and no values
*
* Complete each function below.
* Write each function as a separate recursive definition (do not use more than one helper per function).
* Depth of root==0.
* Height of leaf==0.
* Size of empty tree==0.
* Height of empty tree=-1.
*
* TODO: complete the functions in this file.
* DO NOT change the Node class.
* DO NOT change the name or type of any function (the first line of the function)
*
* Restrictions:
* - no loops (you cannot use "while" "for" etc...)
* - only one helper function per definition
* - no fields (static or non static). Only local variables
*************************************************************************/
public class IntTree {
   private Node root;
   private static class Node {
       public final int key;
       public Node left, right;
       public Node(int key) { this.key = key; }
   }

   public void printInOrder() {
       printInOrder(root);
   }
  
   private void printInOrder(Node n) {
       if (n == null)
           return;
       printInOrder(n.left);
       System.out.println(n.key);
       printInOrder(n.right);
   }

   // the number of nodes in the tree
   public int size() {
       // TODO
       return 0;
   }

   // Recall the definitions of height and depth.
   // in the BST with level order traversal "41 21 61 11 31",
   // node 41 has depth 0, height 2
   // node 21 has depth 1, height 1
   // node 61 has depth 1, height 0
   // node 11 has depth 2, height 0
   // node 31 has depth 2, height 0
   // height of the whole tree is the height of the root

  
   // 20 points
   /* Returns the height of the tree.
   * For example, the BST with level order traversal 50 25 100 12 37 150 127
   * should return 3.
   *
   * Note that the height of the empty tree is defined to be -1.
   */
   public int height() {
       // TODO
       return 0;
   }


   // 20 points
   /* Returns the number of nodes with odd keys.
   * For example, the BST with level order traversal 50 25 100 12 37 150 127
   * should return 3 (25, 37, and 127).
   */
   public int sizeOdd() {
       // TODO
       return -1;
   }

  
   // 20 points
   /* Returns true if this tree and that tree "look the same." (i.e. They have
   * the same keys in the same locations in the tree.)
   * Note that just having the same keys is NOT enough. They must also be in
   * the same positions in the tree.
   */
   public boolean treeEquals(IntTree that) {
       // TODO
       return false;
   }
  
  

   // 10 points
   /* Returns the number of nodes in the tree, at exactly depth k.
   * For example, given BST with level order traversal 50 25 100 12 37 150 127
   * the following values should be returned
   * t.sizeAtDepth(0) == 1       [50]
   * t.sizeAtDepth(1) == 2       [25, 100]
   * t.sizeAtDepth(2) == 3       [12, 37, 150]
   * t.sizeAtDepth(3) == 1       [127]
   * t.sizeAtDepth(k) == 0 for k >= 4
   */
   public int sizeAtDepth(int k) {
       // TODO
       return -1;
   }


   // 10 points
   /*
   * Returns the number of nodes in the tree "above" depth k.
   * Do not include nodes at depth k.
   * For example, given BST with level order traversal 50 25 100 12 37 150 127
   * the following values should be returned
   * t.sizeAboveDepth(0) == 0
   * t.sizeAboveDepth(1) == 1                   [50]
   * t.sizeAboveDepth(2) == 3                   [50, 25, 100]      
   * t.sizeAboveDepth(3) == 6                   [50, 25, 100, 12, 37, 150]
   * t.sizeAboveDepth(k) == 7 for k >= 4       [50, 25, 100, 12, 37, 150, 127]
   */
   public int sizeAboveDepth(int k) {
       // TODO
       return -1;
   }

   // 10 points
   /* Returns true if for every node in the tree has the same number of nodes
   * to its left as to its right.
   *    For example, the BST with level order traversal 50 25 100 12 37 150 127
   * is NOT perfectly balanced. Although most of the nodes (including the root) have the same number of nodes
   * to the left as to the right, the nodes with 100 and 150 do not and so the tree is not perfeclty balanced.
   *
   * HINT: In the helper function, change the return type to int and return -1 if the tree is not perfectly balanced
   * otherwise return the size of the tree. If a recursive call returns the size of the subtree, this will help
   * you when you need to determine if the tree at the current node is balanced.
   */
   public boolean isPerfectlyBalanced() {
       // TODO
       return false;
   }


  
   /*
   * Mutator functions
   * HINT: This is easier to write if the helper function returns Node, rather than void
   * similar to recursive mutator methods on lists.
   */

   // 10 points
   /* Removes all subtrees with odd roots (if node is odd, remove it and its descendants)
   * A node is odd if it has an odd key.
   * If the root is odd, then you should end up with the empty tree.
   * For example, when called on a BST
   * with level order traversal 50 25 100 12 37 150 127
   * the tree will be changed to have level order traversal 50 100 150
   */
   public void removeOddSubtrees () {
       // TODO
   }

   /* ***************************************************************************
   * Some methods to create and display trees
   *****************************************************************************/

   // Do not modify "put"
   public void put(int key) { root = put(root, key); }
   private Node put(Node n, int key) {
       if (n == null) return new Node(key);
       if (key < n.key) n.left = put(n.left, key);
       else if (key > n.key) n.right = put(n.right, key);
       return n;
   }
   // This is what contains looks like
   public boolean contains(int key) { return contains(root, key); }
   private boolean contains(Node n, int key) {
       if (n == null) return false;
       if (key < n.key) return contains(n.left, key);
       else if (key > n.key) return contains(n.right, key);
       return true;
   }
   // Do not modify "copy"
   public IntTree copy () {
       IntTree that = new IntTree ();
       for (int key : levelOrder())
           that.put (key);
       return that;
   }
   // Do not modify "levelOrder"
   public Iterable<Integer> levelOrder() {
       LinkedList<Integer> keys = new LinkedList<Integer>();
       LinkedList<Node> queue = new LinkedList<Node>();
       queue.add(root);
       while (!queue.isEmpty()) {
           Node n = queue.remove();
           if (n == null) continue;
           keys.add(n.key);
           queue.add(n.left);
           queue.add(n.right);
       }
       return keys;
   }
   // Do not modify "toString"
   public String toString() {
       StringBuilder sb = new StringBuilder();
       for (int key: levelOrder())
           sb.append (key + " ");
       return sb.toString ();
   }
  
   public void prettyPrint() {
       if (root == null)
           System.out.println("<EMPTY>");
       else
           prettyPrintHelper(root, "");
   }
  
   private void prettyPrintHelper(Node n, String indent) {
       if (n != null) {
           System.out.println(indent + n.key);
           indent += " ";
           prettyPrintHelper(n.left, indent);
           prettyPrintHelper(n.right, indent);
       }
   }
  
   public static void main(String[] args) {
       IntTree s = new IntTree();
       s.put(15);
       s.put(11);
       s.put(21);
       s.put(8);
       s.put(13);
       s.put(16);
       s.put(18);
       s.printInOrder();
   }  
}

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

The Java code is given below: (Updated code is highlighted)

package hw3;

import java.util.LinkedList;

/* ***********************************************************************
 * A simple BST with int keys and no values
 *
 * Complete each function below.
 * Write each function as a separate recursive definition (do not use more than one helper per function).
 * Depth of root==0.
 * Height of leaf==0.
 * Size of empty tree==0.
 * Height of empty tree=-1.
 *
 * TODO: complete the functions in this file.
 * DO NOT change the Node class.
 * DO NOT change the name or type of any function (the first line of the function)
 *
 * Restrictions:
 * - no loops (you cannot use "while" "for" etc...)
 * - only one helper function per definition
 * - no fields (static or non static). Only local variables
 *************************************************************************/
public class IntTree {
    private Node root;
    private static class Node {
        public final int key;
        public Node left, right;
        public Node(int key) { this.key = key; }
    }

    public void printInOrder() {
        printInOrder(root);
    }

    private void printInOrder(Node n) {
        if (n == null)
            return;
        printInOrder(n.left);
        System.out.println(n.key);
        printInOrder(n.right);
    }

    // the number of nodes in the tree
    public int size() {
        return size(root);
    }

    private int size(Node n)
    {
        if(n == null)
            return 0;
        return size(n.left) + size(n.right) + 1;
    }

    // Recall the definitions of height and depth.
    // in the BST with level order traversal "41 21 61 11 31",
    // node 41 has depth 0, height 2
    // node 21 has depth 1, height 1
    // node 61 has depth 1, height 0
    // node 11 has depth 2, height 0
    // node 31 has depth 2, height 0
    // height of the whole tree is the height of the root


    // 20 points
    /* Returns the height of the tree.
     * For example, the BST with level order traversal 50 25 100 12 37 150 127
     * should return 3.
     *
     * Note that the height of the empty tree is defined to be -1.
     */
    public int height() {
        return height(root);
    }

    private int height(Node n)
    {
        if(n == null)
            return -1;
        return Math.max(height(n.left),height(n.right)) + 1;
    }
    // 20 points
    /* Returns the number of nodes with odd keys.
     * For example, the BST with level order traversal 50 25 100 12 37 150 127
     * should return 3 (25, 37, and 127).
     */
    public int sizeOdd() {
        return sizeOdd(root);
    }
    private int sizeOdd(Node n)
    {
        if(n == null)
            return 0;
        return sizeOdd(n.left) + sizeOdd(n.right) + (n.key & 1); // (n.key & 1) gives 1 if n.key is odd.
    }

    // 20 points
    /* Returns true if this tree and that tree "look the same." (i.e. They have
     * the same keys in the same locations in the tree.)
     * Note that just having the same keys is NOT enough. They must also be in
     * the same positions in the tree.
     */
    public boolean treeEquals(IntTree that) {
        return treeEquals(root, that.root);
    }
    private boolean treeEquals(Node a, Node b)
    {
        if(a == null && b == null)
            return true;
        if(a == null || b == null)
            return false;
        return ((a.key == b.key) && treeEquals(a.left,b.left) && treeEquals(a.right,b.right));
    }


    // 10 points
    /* Returns the number of nodes in the tree, at exactly depth k.
     * For example, given BST with level order traversal 50 25 100 12 37 150 127
     * the following values should be returned
     * t.sizeAtDepth(0) == 1       [50]
     * t.sizeAtDepth(1) == 2       [25, 100]
     * t.sizeAtDepth(2) == 3       [12, 37, 150]
     * t.sizeAtDepth(3) == 1       [127]
     * t.sizeAtDepth(k) == 0 for k >= 4
     */
    public int sizeAtDepth(int k) {
        return sizeAboveDepth(root, k);
    }
    private int sizeAtDepth(Node n, int k)
    {
        if(n == null)
            return 0;
        if(k == 0)
            return 1;
        return sizeAtDepth(n.left, k-1) + sizeAtDepth(n.right, k-1); // add left and right count
    }

    // 10 points
    /*
     * Returns the number of nodes in the tree "above" depth k.
     * Do not include nodes at depth k.
     * For example, given BST with level order traversal 50 25 100 12 37 150 127
     * the following values should be returned
     * t.sizeAboveDepth(0) == 0
     * t.sizeAboveDepth(1) == 1                   [50]
     * t.sizeAboveDepth(2) == 3                   [50, 25, 100]
     * t.sizeAboveDepth(3) == 6                   [50, 25, 100, 12, 37, 150]
     * t.sizeAboveDepth(k) == 7 for k >= 4       [50, 25, 100, 12, 37, 150, 127]
     */
    public int sizeAboveDepth(int k) {
        return sizeAboveDepth(root, k);
    }
    private int sizeAboveDepth(Node n, int k)
    {
        if(n == null)
            return 0;
        if(k == 0) // return from depth k 
            return 1;
        return sizeAboveDepth(n.left, k-1) + sizeAboveDepth(n.right,k-1) + 1;  
    }

    // 10 points
    /* Returns true if for every node in the tree has the same number of nodes
     * to its left as to its right.
     *    For example, the BST with level order traversal 50 25 100 12 37 150 127
     * is NOT perfectly balanced. Although most of the nodes (including the root) have the same number of nodes
     * to the left as to the right, the nodes with 100 and 150 do not and so the tree is not perfeclty balanced.
     *
     * HINT: In the helper function, change the return type to int and return -1 if the tree is not perfectly balanced
     * otherwise return the size of the tree. If a recursive call returns the size of the subtree, this will help
     * you when you need to determine if the tree at the current node is balanced.
     */
    public boolean isPerfectlyBalanced() {
        int ans = isPerfectlyBalanced(root);
        if(ans == -1)
            return false;
        return true;
    }
    private int isPerfectlyBalanced(Node n)
    {
        if(n == null)
            return 0;
        int l = isPerfectlyBalanced(n.left);
        int r = isPerfectlyBalanced(n.right);
        if(l == r)
            return l + r + 1; // returns size if left and right subtree is of same size
        else
            return -1; // otherwise return -1
    }


    /*
     * Mutator functions
     * HINT: This is easier to write if the helper function returns Node, rather than void
     * similar to recursive mutator methods on lists.
     */

    // 10 points
    /* Removes all subtrees with odd roots (if node is odd, remove it and its descendants)
     * A node is odd if it has an odd key.
     * If the root is odd, then you should end up with the empty tree.
     * For example, when called on a BST
     * with level order traversal 50 25 100 12 37 150 127
     * the tree will be changed to have level order traversal 50 100 150
     */
    public void removeOddSubtrees () {
        if (root == null) return;
        /** If the root key is odd then tree becomes empty */
        if (root.key % 2 != 0) {
            root = null;
        }
        removeOddSubtrees(root);
    }

    private void removeOddSubtrees(Node n) {
        if(n == null) return;
        if (n.left != null) {
            /** if left node is odd then left becomes null */
            if (n.left.key % 2 != 0) {
                n.left = null;
            }
            else {
                removeOddSubtrees(n.left);
            }
        }
        if (n.right != null) {
            /** if right node is odd then right becomes null */
            if (n.right.key % 2 != 0) {
                n.right = null;
            }
            else {
                removeOddSubtrees(n.right);
            }
        }
    }

    /* ***************************************************************************
     * Some methods to create and display trees
     *****************************************************************************/

    // Do not modify "put"
    public void put(int key) { root = put(root, key); }
    private Node put(Node n, int key) {
        if (n == null) return new Node(key);
        if (key < n.key) n.left = put(n.left, key);
        else if (key > n.key) n.right = put(n.right, key);
        return n;
    }
    // This is what contains looks like
    public boolean contains(int key) { return contains(root, key); }
    private boolean contains(Node n, int key) {
        if (n == null) return false;
        if (key < n.key) return contains(n.left, key);
        else if (key > n.key) return contains(n.right, key);
        return true;
    }
    // Do not modify "copy"
    public IntTree copy () {
        IntTree that = new IntTree ();
        for (int key : levelOrder())
            that.put (key);
        return that;
    }
    // Do not modify "levelOrder"
    public Iterable<Integer> levelOrder() {
        LinkedList<Integer> keys = new LinkedList<Integer>();
        LinkedList<Node> queue = new LinkedList<Node>();
        queue.add(root);
        while (!queue.isEmpty()) {
            Node n = queue.remove();
            if (n == null) continue;
            keys.add(n.key);
            queue.add(n.left);
            queue.add(n.right);
        }
        return keys;
    }
    // Do not modify "toString"
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (int key: levelOrder())
            sb.append (key + " ");
        return sb.toString ();
    }

    public void prettyPrint() {
        if (root == null)
            System.out.println("<EMPTY>");
        else
            prettyPrintHelper(root, "");
    }

    private void prettyPrintHelper(Node n, String indent) {
        if (n != null) {
            System.out.println(indent + n.key);
            indent += " ";
            prettyPrintHelper(n.left, indent);
            prettyPrintHelper(n.right, indent);
        }
    }

    public static void main(String[] args) {
        IntTree s = new IntTree();
        s.put(15);
        s.put(11);
        s.put(21);
        s.put(8);
        s.put(13);
        s.put(16);
        s.put(18);
        System.out.println("Inorder of tree: ");
        s.printInOrder();
        System.out.println("size of tree: " + s.size());
        System.out.println("size of odd nodes: " + s.sizeOdd());
        System.out.println("height of tree: " + s.height());
        System.out.println("Is perfectly balanced: " + s.isPerfectlyBalanced());
        System.out.println("Size at k depth: " + s.sizeAtDepth(2));
        System.out.println("Size at above depth k: " + s.sizeAboveDepth(2));
        s.removeOddSubtrees();
        System.out.println("Tree after removal of odd nodes: ");
        s.prettyPrint();
    }
}

Sample Output:

If the answer helped please upvote, it means a lot and for any query please comment.

Add a comment
Know the answer?
Add Answer to:
package hw3; import java.util.LinkedList; /* *********************************************************************** * A simple BST with int keys and no values...
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
  • ​​​​​ You should now be able to edit the IntTree class. Implement each of the functions labeled...

    ​​​​​ You should now be able to edit the IntTree class. Implement each of the functions labeled with You are not allowed to use any kind of loop in your solutions. You may not modify the Node class in any way You may not modify the function headers of any of the functions already present in the file. You may not add any fields to the IntTree class. You may not change or remove the line that reads “package hw2;”...

  • Java help! Please help complete the min method below in bold. import java.util.Arrays; import java.util.ArrayList; import...

    Java help! Please help complete the min method below in bold. import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * Provides an implementation of a binary search tree * with no balance constraints, implemented with linked nodes. * * * */ public class Bst<T extends Comparable<T>> implements Iterable<T> { ////////////////////////////////////////////////////////////////// // I M P L E M E N T T H E M I N M E T H O D B E L O W...

  • Question B1 You are given the following Java classes: public class Queue { private static class...

    Question B1 You are given the following Java classes: public class Queue { private static class Node { Object object; Node next; Node () { object = null; next = null; } Node (Object object, Node next) { this.object = object; this.next = next; private Node header; private int size = 0; // size shows the no of elements in queue public Object dequeue () { if (size == 0 ) { return null; else { Object remove_object = header.object;...

  • using java to write,show me the output. please write some common. You CAN NOT use inbuild...

    using java to write,show me the output. please write some common. You CAN NOT use inbuild functions for Tree ADT operations. using code below to finsih public class Main {    public static void main(String[] args) {        BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.left.left.left = new Node(8); tree.root.left.left .right= new Node(9);...

  • In this assignment, you will add several methods to the Binary Search Tree. You should have compl...

    In this assignment, you will add several methods to the Binary Search Tree. You should have completed the following three methods in the lab: public void insert(Key key, Value value) public Value get(Key key) public void inorder(Node root) For this assignment, you will implement the following: public void remove(Node root, Key key) public Key getMin(Node n) public Key getMax(Node n) public int height(Node n) The main method contains the statements to check whether your implementation works. You need to change...

  • Hello, I've been working on this for a while and I can't figure the rest out....

    Hello, I've been working on this for a while and I can't figure the rest out. Need asap if anyone can help. maxBSt,minBST,isBST, and inOrder package lab7; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; public class TreeExercise {    /*    * Construct BST from preorder traversal    */    public static Node<Integer> consBSTfromPreOrder(int[] arr, int start, int end)    {                       if(start > end) return null;               Node<Integer> root = new Node<Integer>(arr[start],...

  • BST JAVA FILE import java.util.*; public class BST <E extends Comparable <E>> {    private TreeNode<E>...

    BST JAVA FILE import java.util.*; public class BST <E extends Comparable <E>> {    private TreeNode<E> overallRoot;    public BST() {        overallRoot = null;    }    // ************ ADD ************ //    public void add(E addThis) {        if (overallRoot == null) {            overallRoot = new TreeNode<>(addThis);        } else {            add(overallRoot, addThis);        }    }    private TreeNode<E> add(TreeNode<E> node, E addThis) {        if...

  • JAVA QUESTION: *******THE QUESTION:******** /** numberOfNodesAtDepth    *    * Returns the number of nodes with...

    JAVA QUESTION: *******THE QUESTION:******** /** numberOfNodesAtDepth    *    * Returns the number of nodes with depth == d    * Precondition: none    *    * param: d the depth to search for    *    * hint: use a recursive helper function    *        * ToDo 4    */    public int numNodesAtDepth(int d) {        return -1;    } **********USEFUL CODE FROM THE ASSIGNMENT:*********** public class simpleBST<Key extends Comparable<Key>, Value> {    private Node root;            ...

  • Can you take a look at my code that why the maxDepth function is not working?...

    Can you take a look at my code that why the maxDepth function is not working? public class BinaryTree {          class Node{        int key;        Node left,right;               public Node(int item) {            key = item;            left = right = null;        }    }       Node root;       public void BinaryTree(){        root = null;    }           void...

  • 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...

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