Question

Need help with this binary tree program. I will give a thumbs up for anybody who...

Need help with this binary tree program. I will give a thumbs up for anybody who helps.

Source Code:

import java.util.Random;
import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;
import java.util.ArrayList;
public class Trees {
public static int[] prepareData(int[] data){
/*
Data is prepared by inserting random values
between 1 and data.length. Data items may be assumed to
be unique.
Please refer to lab spec for the problem definiton.
*/
ArrayList list = new ArrayList();
for (int i=0; i< data.length; i++) {
list.add(i);
}
Collections.shuffle(list);

for (int i=0; i < data.length; i++) {
data[i] = list.get(i);
}
return data;
}
public static int[] getChildren(int[] data, int node){
int[] res = new int[2];
/*
Add logic here
*/
return res;
}
public static int getParent(int[] data, int node){
int res = 0;
/* Add logic here */
return res;
}
public static int[] getAncestors(int[] data, int node){
/* Get Ancestors */
/* here I am finding the highest power of 2 closer to the node (pos) */
int size = (int)Math.pow(2, Math.floor(Math.log(node+1) / Math.log(2)));
/* here I am finding the log base 2 of the value computed above
-- this will give me the size of the ancestor set. */
size = (int) (Math.log(size) / Math.log(2));
int[] res = new int[size];

/* Figure out the algorithm.
Add required logic here, can be done mathematically
or iteratively (programmatic).*/

return res;
}
public static int[] getDescendents(int[] data, int node){
/* Get Decendents */
int[] res;
/* how to identify if a node is a leaf node?
identifying the root node is easy.
see how I had identified the leaf node below.
I need to do this to calculate the size of the
decendents set.
*/
int leaf_start = (int) Math.floor((double)data.length/2) + 1;
if (node >= leaf_start)
res = new int[0];
else{
int lower = (int)Math.pow(2, Math.floor(Math.log(node+1) / Math.log(2)));
/* here I am finding the log base 2 of the value
computed above */

lower = (int) (Math.log(lower) / Math.log(2));
int higher = (int)Math.pow(2, Math.floor(Math.log(data.length) / Math.log(2)));
/* here I am finding the log base 2 of the value
computed above */

higher = (int) (Math.log(higher) / Math.log(2));
res = new int[higher-lower];
}

/* Figure out the algorithm.
Add required logic here, can be done mathematically
or iteratively (programmatic).*/


return res;
}
public static int findDepth(int[] data, int node){
/* Find Depth */
int res = 0;

/* add required logic here */

return res;
}
public static int findHeight(int[] data, int node){
/* Find Height */
int res = 0;

/* add required logic here */

return res;
}

public static boolean isBalanced(int[] data){
/* Check if the tree is balanced or not. */
boolean res = false;

/* add required logic here */

return res;
}


public static void main(String[] args) {
/*
Assume binary tree, either complete or atmost complete.
But not in-complete.
*/
System.out.println("Enter the no of elements:");
Random rand = new Random();
Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
int[] raw_data = new int[count];
int[] raw_data_populated = prepareData(raw_data);
System.out.println("Array: " + Arrays.toString(raw_data_populated));

/* The line below will print the output.
Do not uncomment this lines. */

System.out.println("Welcome to the trees structure:");
while(true){
System.out.println("------------------------------------------------");
System.out.println("Please make the following choice to get started:");
System.out.println("1 to get Children\n2 to get Parent \n" +
"3 to get Ancestors \n4 to get Descendents \n" +
"5 to get Depth \n6 to get Height \n7 to check balance");
int choice = scan.nextInt();
if (choice == 1){
/* Get children nodes */
// node is the Position no in the array
System.out.println("Tell me the node no(pos - start from 0):");
int node = scan.nextInt();
int[] children = getChildren(raw_data_populated, node);
System.out.println("children:" + Arrays.toString(children));
}
else if (choice == 2){
/* Get parent node */
// node is the Position no in the array
System.out.println("Tell me the node no(pos - start from 0):");
int node = scan.nextInt();
int parent = getParent(raw_data_populated, node);
System.out.println("parent:" + parent);
}
else if (choice == 3){
/* Get ancestors */
// node is the Position no in the array
System.out.println("Tell me the node no(pos - start from 0):");
int node = scan.nextInt();
int[] ancestors = getAncestors(raw_data_populated, node);
System.out.println("ancestors:" + Arrays.toString(ancestors));
}
else if (choice == 4){
/* Get descendents */
// node is the Position no in the array
System.out.println("Tell me the node no(pos - start from 0):");
int node = scan.nextInt();
int[] descendents = getDescendents(raw_data_populated, node);
System.out.println("descendents:" + Arrays.toString(descendents));
}
else if (choice == 5){
/* Get depth */
// node is the Position no in the array
System.out.println("Tell me the node no(pos - start from 0):");
int node = scan.nextInt();
int depth = findDepth(raw_data_populated, node);
System.out.println("depth:" + depth);
}
else if (choice == 6){
/* Get height */
// node is the Position no in the array
System.out.println("Tell me the node no(pos - start from 0):");
int node = scan.nextInt();
int height = findHeight(raw_data_populated, node);
System.out.println("height:" + height);
}
else if (choice == 7){
/* Check if tree is balanced */
boolean bal = isBalanced(raw_data_populated);
System.out.println("balance status:" + bal);
}
else{
System.out.println("Invalid choice. Please try again.");
continue;
}
System.out.println("------------------------------------------------");
System.out.println("Do you want to try again? y/n");
char repeat = scan.next().charAt(0);
repeat = Character.toLowerCase(repeat);
if (repeat == 'y')
continue;
else
break;
}
}
}

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

I have tried solving the problem your way and I have pasted the solution below

import java.util.Scanner;


class Node
{
    Integer data;
    Node left;
    Node right;
    Node()
    {
        data = null;
        left = null;
        right = null;
    }
}
class BinaryTree
{
    Node head;
    Scanner input = new Scanner(System.in);
    BinaryTree()
    {
        head = null;
    }

    public void createNode(Node temp,Node newnode) 
    {

        if(head==null)
        {
            System.out.println("No value exist in tree, the value just entered is set to Root");
            head = newnode;
            return;
        }
        if(temp==null)
            temp = head;

        System.out.println("where you want to insert this value, l for left of ("+temp.data+") ,r for right of ("+temp.data+")");
        char inputValue=input.next().charAt(0); 
        if(inputValue=='l'){
            if(temp.left==null)
            {
                temp.left=newnode;
                System.out.println("value got successfully added to left of ("+temp.data+")");
                return;
            }else  {
                System.out.println("value left to ("+temp.data+") is occupied 1by ("+temp.left.data+")");
                createNode(temp.left,newnode);
            }
        }
        else if(inputValue=='r')
        {
            if(temp.right==null)
            {
                temp.right=newnode;
                System.out.println("value got successfully added to right of ("+temp.data+")");
                return;

            }else  {
                System.out.println("value right to ("+temp.data+") is occupied by ("+temp.right.data+")");
                createNode(temp.right,newnode);
            }

        }else{
            System.out.println("incorrect input plz try again , correctly");
            return;
        }

    }
    public Node generateTree(){
        int [] a = new int[10];
        int index = 0; 
        while(index<a.length){
            a[index]=getData();
            index++;
        }
        if(a.length==0 ){
            return null;
        }
        Node newnode= new Node();
        /*newnode.left=null;
        newnode.right=null;*/
        return generateTreeWithArray(newnode,a,0);

    }
    public Node generateTreeWithArray(Node head,int [] a,int index){

        if(index >= a.length)
            return null;
        System.out.println("at index "+index+" value is "+a[index]);
        if(head==null)
            head= new Node();
        head.data = a[index];
        head.left=generateTreeWithArray(head.left,a,index*2+1);
        head.right=generateTreeWithArray(head.right,a,index*2+2);
        return head;
    }

    public Integer getData()
    {
        System.out.println("Enter the value to insert:");
        return (Integer)input.nextInt();
    }

    public void print()
    {
        inorder(head);
    }
    public void inorder(Node node)
    {
        if(node!=null)
        {
            inorder(node.left);
            System.out.println(node.data);
            inorder(node.right);
        }
        else
            return;
    }
}

public class BinaryTreeWorker
{
    static BinaryTree treeObj = null;
    static Scanner input = new Scanner(System.in);
    public static void displaymenu()
    {
        int choice;
        do{
            System.out.print("\n Basic operations on a tree:");
            System.out.print("\n 1. Create tree  \n 2. Insert \n 3. Search value \n 4. print list\n 5. generate a tree \n Else. Exit \n Choice:");
            choice = input.nextInt();

            switch(choice)
            {
                case 1:
                    treeObj = createBTree();
                    break;
                case 2:
                    Node newnode= new Node();
                    newnode.data = getData();
                    newnode.left=null;
                    newnode.right=null;
                    treeObj.createNode(treeObj.head,newnode);
                    break;
                case 3:
                    //searchnode();
                    break;
                case 4:
                    System.out.println("inorder traversal of list gives follows");
                    treeObj.print();
                    break;
                case 5:
                    Node tempHead = treeObj.generateTree();
                    System.out.println("inorder traversal of list with head = ("+tempHead.data+")gives follows");
                    treeObj.inorder(tempHead);
                    break;
                default:
                    return;
            }       
        }while(true);
    }
    public static Integer getData()
    {
        System.out.println("Enter the value to insert:");
        return (Integer)input.nextInt();
    }
    public static BinaryTree createBTree()
    {
        return new BinaryTree();
    }
    public static void main(String[] args)
    {
        displaymenu();
    }
}
Add a comment
Know the answer?
Add Answer to:
Need help with this binary tree program. I will give a thumbs up for anybody who...
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
  • Doubly Linked List Is there a way to further modify/simplify/improve this program? I was thinking of maybe changing how...

    Doubly Linked List Is there a way to further modify/simplify/improve this program? I was thinking of maybe changing how to get size. I'm not sure. import java.util.Scanner; /* Class Node */ class Node { protected int data; protected Node next, prev; /* Constructor */ public Node() { next = null; prev = null; data = 0; } /* Constructor */ public Node(int d, Node n, Node p) { data = d; next = n; prev = p; } /* Function...

  • Hi I need help with a java program that I need to create a Airline Reservation...

    Hi I need help with a java program that I need to create a Airline Reservation System I already finish it but it doesnt work can someone please help me I would be delighted it doesnt show the available seats when running the program and I need it to run until someone says no for booking a seat and if they want to cancel a seat it should ask the user to cancel a seat or continue booking also it...

  • Doubly Linked List The assignment is to modify the below code in any way (like changing the method of a function). Time...

    Doubly Linked List The assignment is to modify the below code in any way (like changing the method of a function). Time complexity is omitted. Any methods/functions below could be changed into something different. I was thinking of changing the method of getting size of list and maybe change from numbers to letters for nodes. import java.util.Scanner; /* Class Node */ class Node { protected int data; protected Node next, prev; /* Constructor */ public Node() { next = null;...

  • need help editing or rewriting java code, I have this program running that creates random numbers...

    need help editing or rewriting java code, I have this program running that creates random numbers and finds min, max, median ect. from a group of numbers,array. I need to use a data class and a constructor to run the code instead of how I have it written right now. this is an example of what i'm being asked for. This is my code: import java.util.Random; import java.util.Scanner; public class RandomArray { // method to find the minimum number in...

  • Please help me to solve the problem with java language! An implementation of the Merge Sort...

    Please help me to solve the problem with java language! An implementation of the Merge Sort algorithm. Modify the algorithm so that it splits the list into 3 sublists (instead of two). Each sublist should contain about n/3 items. The algorithm should sort each sublist recursively and merge the three sorted sublists. The traditional merge sort algorithm has an average and worst-case performance of O(n log2 n). What is the performance of the 3-way Merge Sort algorithm? Merge Sort algorithm...

  • Java Assignment Calculator with methods. My code appears below what I need to correct. What I...

    Java Assignment Calculator with methods. My code appears below what I need to correct. What I need to correct is if the user attempts to divide a number by 0, the divide() method is supposed to return Double.NaN, but your divide() method doesn't do this. Instead it does this:     public static double divide(double operand1, double operand2) {         return operand1 / operand2;     } The random method is supposed to return a double within a lower limit and...

  • I have added a little Code but I need help with the rest. /** A class...

    I have added a little Code but I need help with the rest. /** A class of stacks whose entries are stored in a chain of nodes. Implement all methods in MyStack class Main Reference : text book or class notes Do not change or add data fields */ package PJ2; public class MyStack<T> implements StackInterface<T> {    // Data fields    private Node<T> topNode; // references the first node in the chain    private int numberOfEntries;       public...

  • My Question is: I have to modify this program, even a small modification is fine. Can...

    My Question is: I have to modify this program, even a small modification is fine. Can anyone give any suggestion and solution? Thanks in Advanced. import java.util.*; class arrayQueue { protected int Queue[]; protected int front, rear, size, len; public arrayQueue(int n) { size = n; len = 0; Queue = new int[size]; front = -1; rear = -1; } public boolean isEmpty() { return front == -1; } public boolean isFull() { return front == 0 && rear ==size...

  • please make a pretty JAVA GUI for this code this is RED BLACK TREE and i...

    please make a pretty JAVA GUI for this code this is RED BLACK TREE and i Finished code already jus need a JAVA GUI for this code ... if poosible make it pretty to look thanks and please make own GUI code base on my code thanks ex: (GUI only have to show RBTree) ---------------------------------------- RBTree.java import java.util.Stack; public class RBTree{    private Node current;    private Node parent;    private Node grandparent;    private Node header;    private Node...

  • Hey i got the program to work but i cant get the merge sorter from big...

    Hey i got the program to work but i cant get the merge sorter from big to little import java.util.*; class MergeSorter {    public static void sort(int[] a)    { if (a.length <= 1) { return; } int[] first = new int[a.length / 2]; int[] second = new int[a.length - first.length]; for (int i = 0; i < first.length; i++) {    first[i] = a[i]; } for (int i = 0; i < second.length; i++) {    second[i] =...

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