Question

Hierarchical structures: Write a java class to implement a Multi-way tree, with an appropriate constructor and...

Hierarchical structures:

Write a java class to implement a Multi-way tree, with an appropriate constructor and methods for the following:

            Methods to find and insert on the tree.

            Method to return the height of the tree.

Methods to output the values from this tree in any one of the following ways:

            Pre-order:        Left to right order of siblings

            Post-order:      Right to left order of siblings

            Level order:    Left to right order of siblings

            Method to store the tree to a file per the format used for reading the file.

Write a Java application that reads an input file that describes a flattened tree and constructs the corresponding tree. The format of the is as follows:

The first line has an integer value, m, for an m-way tree described in the file.

The second line indicates the value at the root.

Each subsequent line will describe a node in the tree. There will be up to m+1 integer values separated by a space. The first is the value at the node, and the subsequent values indicate the values in its children nodes.

Example:

3                                  The file describes a 3-way tree

1                                  The root has value 1

1 8 22 29                     Node with value 1 has children with values 8, 22, and 29

8 3 5 17

3 16 19 32

22 42                           Node with value 22 has a child with value 42.

19 10 15

42 13 18 49 55

29 4 9

Your implementation should handle a value of m read from the file. There will be any number of input lines.  A value will be described as a child before it is described with children i.e. parent node will be described before its children. Use recursion and arrays. Note that the tree is not a search-tree.

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

//java program to print a multi way tree

package com;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

class MultiWayTree<T extends Comparable<T>> {
   // left subtree
   MultiWayTree<T> left;
   //right subtree
   MultiWayTree<T> right;
   //elements of tree
   T data;
   //Constructor
   public MultiWayTree(T data) {
   this.data = data;
   this.left = null;
   this.right = null;
   }

   public void insert(T value) {
   //value <= data
   if(value.compareTo(data) <= 0) {
   if(left == null) {
   // Insert at empty tree
   left = new MultiWayTree<T>(value);
   }
   else {
  
   left.insert(value);
   }
   }
   else { // value > data
   if(right == null) {
   // Insert at empty tree
   right = new MultiWayTree<T>(value);
   }
   else {
     
   right.insert(value);
   }
   }
      
   }
   public boolean find(T value) {
   if(value.compareTo(data) == 0) {
   // Value found
   return true;
   }
   else if(value.compareTo(data) < 0) {
   return (left == null)
   ? false //there are no more MultiWayTrees in left subtree to check
   : left.find(value); // Continue searching left subtree
   }
   else { // data.compareTo(value) > 0
   return (right == null)
   ? false // Not found; there are no more MultiWayTrees in right subrtree to check
   : right.find(value); // Continue searching right subtree
   }
   }

   //preOrder of tree
   public void preOrder() {
   if(left != null) {
   left.preOrder();
   }
   System.out.print(data + " ");
     
   }
   //method for postOrder
   public void postOrder() {
   System.out.print(data + " ");

   if(right != null) {
   right.postOrder();
   }
   }

   public static void main(String[] args) throws IOException {
       List<String> filedata = new ArrayList<String>();
         
       //read tree from a text file
   try
   {
   FileInputStream in = new FileInputStream("input.txt");
   BufferedReader br = new BufferedReader(new InputStreamReader(in));
   String line;
     
   while((line = br.readLine())!= null)
   {
       MultiWayTree<String> root = new MultiWayTree<String>( line);
   filedata.add(line);
  
   }
   br.close();
   }catch(Exception e)
   {
   System.out.println(e);
   }
   System.out.println(filedata);
   //write tree to a text file
   FileWriter fw=new FileWriter(new File("output.txt"));
   for(String f:filedata)
   {
   fw.write(f);
   }
   fw.close();   
   }
   }

//input.txt

3
1
1 8 22 29
8 3 5 17
3 16 19 32
22 42   
19 10 15
42 13 18 49 55
29 4 9

output.txt created

Add a comment
Know the answer?
Add Answer to:
Hierarchical structures: Write a java class to implement a Multi-way tree, with an appropriate constructor and...
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
  • java Description You are to create a class named BinaryTree. This will simulate a balanced and...

    java Description You are to create a class named BinaryTree. This will simulate a balanced and ordered binary tree. You also need to create a TreeNode class, which defines the data contained in each node of the tree. In this case, it is an integer. Remember that the node also needs a way to track back to its parent, as well as its left and right children. For the purpose of this assignment, each node should also contain an indication...

  • Using the following implementation of Tree class Node   {   public int iData;              // data item (key)   public...

    Using the following implementation of Tree class Node   {   public int iData;              // data item (key)   public double dData;           // data item   public Node leftChild;         // this node's left child   public Node rightChild;        // this node's right child   public void displayNode()      // display ourself      {      System.out.print('{');      System.out.print(iData);      System.out.print(", ");      System.out.print(dData);      System.out.print("} ");      }   }  // end class Node //------------------------------------------------------------------ import java.io.IOException; import java.util.Stack; public class Tree { private Node root; // first node of tree // ------------------------------------------------------------- public Tree() // constructor { root = null; }...

  • *****************************In Java***************************************In Java***********************************In Java************************* In this problem, you will implement various algorithms operating on binary search...

    *****************************In Java***************************************In Java***********************************In Java************************* In this problem, you will implement various algorithms operating on binary search trees. We have provided with you a standard implementation of a generic BST in BinarySearchTree.java. Note that this class is an abstract class, which means that some of its methods are not implemented. In previous assignments, you have implemented interfaces which specified methods that you needed to write. Very similarly, an abstract class is a class with some unimplemented methods (it can be thought...

  • 1. Construct a Binary Search Tree 50 Write code to implement a BST. Implement an add) method and ...

    C++ program 1. Construct a Binary Search Tree 50 Write code to implement a BST. Implement an add) method and a remove) method. Use the following input to construct a BST: 50,20,75,98,80,31,150, 39, 23,11,77 20 75 31 98 0 (150 Hint on removing If the node to be removed is: a leaf node a node with a left child only a node with a right child only a node with both children Then take this action replace with null replace...

  • show output as well Design a class called TreeNode (the class java file should be called...

    show output as well Design a class called TreeNode (the class java file should be called TreeNode.java) that encodes a binary tree node with integral values, with the following (exact) fields and methods/constructors: Description The integral data store in the node Link to the left subtree Link to the right subtree Fields and Methods Fields Data Left Right Methods TreeNode A constructor with no parameters that initialized the fields Design a class called TreeNodeWrapper (the class java file should be...

  • Removing Nodes from a Binary Tree in Java This section requires you to complete the following...

    Removing Nodes from a Binary Tree in Java This section requires you to complete the following method within BinaryTree.java: public void remove(K key) { } The remove method should remove the key from the binary tree and modify the tree accordingly to maintain the Binary Search Tree Principle. If the key does not exist in the binary tree, no nodes should be removed. In case there is a non-null left child, it should take the place of the removed node....

  • The code should be in java. Question: In an infinite binary tree where every node has...

    The code should be in java. Question: In an infinite binary tree where every node has two children, the nodes are labelled in row order. In each row, the labeling is left to right. Given the label of a node in this tree, please write a method to return the labels in the path from the root of the tree to the node with that label. Your algorithm should have time complexity of O ( log ⁡ n ). Example...

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

  • Does not pass the testcase testDTreeAdvancedReRootchangesParent Java I'm trying to extend the implementation of a general...

    Does not pass the testcase testDTreeAdvancedReRootchangesParent Java I'm trying to extend the implementation of a general tree with new operations that change the structure of the tree. I've created 5 classes: Node.java, SimpleNode.java, Tree.java, RerootableTree.java and SimpleTree.java(which is the main java class that I need to change). The code does not pass ONE TESTCASE : testDTreeAdvancedReRootchangesParent The code passes all the other testcases except theone mentioned above. This is because in the SimpleTree.java the method "reRoot(Node newRoot)" is most likely...

  • Write a recursive function (C++) that searches a binary tree that is NOT ordered like a...

    Write a recursive function (C++) that searches a binary tree that is NOT ordered like a BST. In other words, there is no ordering relationship among the parent, child or sibling node values. Use the following prototype and data structure: struct node { node *left; node *right; int val; }; // First parameter: pointer to a node // Second parameter: the value to find bool searchValue(node *, int); The function searchValue() should return true if the integer value in the...

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