Question

Program in JAVA: A Perfect binary tree is a complete binary tree with all levels fully...

Program in JAVA: A Perfect binary tree is a complete binary tree with all levels fully filled. Add a method in the BST class to return true if the tree is a perfect binary tree.(Hint: The number of nodes in the nonempty perfect binary tree is 2 raised to the power of height - 1) (/** returns true if the tree is a perfect binary tree, boolean isPerfectBST() **/)

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

package aug02;
public class BinaryTree {

        public int value;
        private BinaryTree leftChild;
        private BinaryTree rightChild;

        /**
         * Constructor for BinaryTree
         */
        public BinaryTree(int value, BinaryTree leftChild, BinaryTree rightChild) {
                this.value = value;
                this.leftChild = leftChild;
                this.rightChild = rightChild;
        }

        public BinaryTree(int value) {
                this(value, null, null);
        }
        
        public int getValue() {
                return value;
        }

        public BinaryTree getLeftChild() {
                return leftChild;
        }

        public BinaryTree getRightChild() {
                return rightChild;
        }

        public void setLeftChild(BinaryTree leftChild) {
                this.leftChild = leftChild;
        }

        public void setRightChild(BinaryTree rightChild) {
                this.rightChild = rightChild;
        }

        public static void printInorder(BinaryTree start) {
                if(start.getLeftChild() != null) {
                        printInorder(start.getLeftChild());
                }
                System.out.print(" " + start.getValue());
                if(start.getRightChild() != null) {
                        printInorder(start.getRightChild());
                }
        }
        
        
        public static BinaryTree createFullBST(int depth) {
                BinaryTree root = new BinaryTree((int) Math.pow(2, depth));
                
                addFullBSTNodes(root, 0, depth);
                
                return root;
        }
        
        private static void addFullBSTNodes(BinaryTree start, int currentDepth, int maxDepth) {
                // base case
                if(currentDepth == maxDepth) {
                        return;
                }
                int rootValue = start.getValue();
                int diff = (int) Math.pow(2, maxDepth - currentDepth - 1);
                BinaryTree left = new BinaryTree(rootValue - diff);
                start.setLeftChild(left);
                BinaryTree right = new BinaryTree(rootValue + diff); 
                start.setRightChild(right);
                
                addFullBSTNodes(left, currentDepth + 1, maxDepth);
                addFullBSTNodes(right, currentDepth + 1, maxDepth);
        }

        public int countNodesInRange(int min, int max) {
                int count = 0;
                if(value >= min && value <= max) {
                        count++;
                }
                if(leftChild != null) {
                        count += leftChild.countNodesInRange(min, max);
                }
                if(rightChild != null) {
                        count += rightChild.countNodesInRange(min, max);
                }
                return count;
        }

        
        public int maxValue() {
                int max = value;
                if(leftChild != null) {
                        int val = leftChild.maxValue();
                        if(val > max) {
                                max = val;
                        }
                }
                if(rightChild != null) {
                        int val = rightChild.maxValue();
                        if(val > max) {
                                max = val;
                        }
                }
                return max;
        }
        
        public int nodesWithNoSons() {
                int count = 0;
                if(leftChild == null && rightChild == null) {
                        return 1;
                }
                if(leftChild != null) {
                        count += leftChild.nodesWithNoSons();
                } 
                if(rightChild != null) {
                        count += rightChild.nodesWithNoSons();
                }
                return count;
        }

        public int height() {
                int left = 0, right = 0;
                if(leftChild != null) {
                        left = leftChild.height();
                }
                if(rightChild != null) {
                        right = rightChild.height();
                }
                return 1 + Math.max(left, right);
        }
        
        public int numNodes() {
                int left = 0, right = 0;
                if(leftChild != null) {
                        left = leftChild.numNodes();
                }
                if(rightChild != null) {
                        right = rightChild.numNodes();
                }
                return 1 + left + right;
        }
        
        public boolean isPerfectBST() {
                int n = numNodes();
                int h = height();
                return ((n + 1) == Math.pow(2, h));
        }
        
        public static void main(String args[]) {
                BinaryTree tree = createFullBST(6);
                printInorder(tree);
                System.out.println();
                
                System.out.println("Max value: " + tree.maxValue());
                System.out.println("nodes between 59 and 112: " + tree.countNodesInRange(59, 112));
                System.out.println("nodes with no sons: " + tree.nodesWithNoSons());
                System.out.println("Is perfect: " + tree.isPerfectBST());
        }
        

}


Please upvote, as i have given the exact answer as asked in question. Still in case of any issues in code, let me know in comments. Thanks!

Add a comment
Know the answer?
Add Answer to:
Program in JAVA: A Perfect binary tree is a complete binary tree with all levels fully...
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
  • 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...

  • Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to com...

    Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to completely test every method in the BST class to ensure the class meets all its requirements. You should read the Listing 25.5: TestBST.java for an idea of what your program should look like. Listing 25.4 BST.java public class BST> extends AbstractTree { protected TreeNode...

  • Construct a Binary Search Tree (BST) program in C++. The program is required to: 1) load...

    Construct a Binary Search Tree (BST) program in C++. The program is required to: 1) load the BST from a dataset (I will provide the datasets-see below) in the order they exist in the dataset. 2) after the BST is built analyze the BST and display the following values: 2.1) the smallest branch height 2.2) the highest branch height 2.3) the number of nodes in the tree 2.4) the determination if the tree is balanced 2.5) the determination if the...

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

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

  • PYTHON QUESTION... Building a Binary Tree with extended Binary Search Tree and AVL tree. Create a...

    PYTHON QUESTION... Building a Binary Tree with extended Binary Search Tree and AVL tree. Create a class called MyTree with the methods __init__(x), getLeft(), getRight(), getData(), insert(x) and getHeight(). Each child should itself be a MyTree object. The height of a leaf node should be zero. The insert(x) method should return the node that occupies the original node's position in the tree. Create a class called MyBST that extends MyTree. Override the method insert(x) to meet the definitions of a...

  • Design a divide-and-conquer algorithm for computing the number of levels in a binary tree. In particular,...

    Design a divide-and-conquer algorithm for computing the number of levels in a binary tree. In particular, the algorithm should return 0 and 1 for the empty and single-node trees respectively. Please provide the pseudocode for your algorithm. What is the running time of your algorithm in the worst case using O() notation? Design a divide-and-conquer algorithm for computing the number of levels in a COMPLETE binary tree. In particular, the algorithm should return 0 and 1 for the empty and...

  • Consider the partial implementation of a Binary Search Tree (BST) class. For simplicity, each Node stores...

    Consider the partial implementation of a Binary Search Tree (BST) class. For simplicity, each Node stores only the key. Add a public member function to class BST that returns the largest absolute value in the tree. The language is C++ Want the height #4 Coding [6 points] Consider the partial implementation of a Binary Search Tree (BST) class. For simplicity, each Node stores only the key. Add a public member function to class BST that returns the height of the...

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

  • A balanced binary tree is a binary tree structure in which the left and right subtrees of every node differ

    Data structures C++1- A balanced binary tree is a binary tree structure in which the left and right subtrees of every node differ in height by no more than 1 Out of the following choices, which is the minimum set of nodes, if removed, will make the BST balanced?2- Which of the following is true for Red-Black Trees ? Select all choices that apply! Select one or more: a. For each node in the tree, all paths from that node to any leaf nodes contain...

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