Solved

Constructing an M way tree

Posted on 2007-04-04
13
391 Views
Last Modified: 2011-09-20
I'm supposed to read a file in a format like this and then construct a tree from it.

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
29 4 9

I have the generic class GTree and i'm not really sure how to construct the tree though in this format. I have started my main class and just read the file. I have never constructed a tree before so i really don't konw how to get started. For the root do i just do a tree.insert(1)? and then if that's how i do that, how do i choose which child to add children to? Also i have no idea how to make this an M-way tree either. Any help would be great.

package binaryTree;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import treeProgram.GTree;

public class GenerateThatTree {

      public static void main(String[] args) throws FileNotFoundException {
            
            GTree<Integer> tree = new GTree<Integer>();
            tree.insert(1);
            
            String fileName = "tree.dat";
            Scanner fromFile = null;
            System.out.println("The file " + fileName + " contains the following lines:");
            
            fromFile = new Scanner(new File(fileName));
            
            while(fromFile.hasNextLine()){
                  String line = fromFile.nextLine();
                  System.out.println(line);
            }
            fromFile.close();
      }

}

package treeProgram;
import java.util.LinkedList;

public class GTree<T extends Comparable> {

      private T data;
      private GTree<T> left;
      private GTree<T> right;
      private GTree<T> root;
      
      public GTree(){
            this(null);
      }
      
      public GTree(T data){
            this(data, null, null);
      }
      
      public GTree(T data, GTree<T>leftChild, GTree<T>rightChild){
            this.data = data;
            left = leftChild;
            right = rightChild;
      }
      
      public T getData(){
            return this.data;
      }
      
      public void setData(T data){
            this.data = data;
      }
      
      public GTree<T> getRightChild(){
            return right;
      }
      
      public GTree<T> getLeftChild(){
            return left;
      }
      
      public void setLeftChild(GTree<T> leftChild){
            left = leftChild;
      }
      
      public void setRightChild(GTree<T> rightChild){
            right = rightChild;
      }
      
      public int getHeight(){
            return getHeight(this);
      }
      
      public int getHeight(GTree<T> node){
            int height = 0;
            
            if(node != null){
                  height = 1 + Math.max(getHeight(node.left), getHeight(node.right));
            }
            return height;
      }
      
      public void preOrderTraverse(){
            preOrderTraverse(root);
      }
      
      public void preOrderTraverse(GTree<T> node){
            if(node != null){
                  System.out.println(node.getData());
                  preOrderTraverse(node.getLeftChild());
                  preOrderTraverse(node.getRightChild());
            }
      }
      
      public void postOrderTraverse(){
            postOrderTraverse(root);
      }
      
      public void postOrderTraverse(GTree<T> node){
            if(node != null){
                  postOrderTraverse(node.getRightChild());
                  postOrderTraverse(node.getLeftChild());
                  System.out.println(node.getData());
            }
      }
      
       public void levelOrderTraverse(){
              this.levelOrderTraverse(this);
          }

          public void levelOrderTraverse(GTree<T> root){
              LinkedList<GTree<T>> queue = new LinkedList<GTree<T>>();
              queue.addLast(this);

              while (queue.size() > 0){
                  GTree<T> node = queue.removeFirst();
                  System.out.println(node.getData());
                  
                  if (node.getLeftChild() != null){
                      queue.addLast(node.getLeftChild());
                  }
                  
                  if (node.getRightChild() != null){
                      queue.addLast(node.getRightChild());
                  }
              }
          }
      
          public GTree<T> find(T data){
              if(this.getData() == data)
                  return this;

              if(this.left != null){
                  GTree<T> leftFind = this.left.find(data);
                  if(leftFind != null)
                      return leftFind;
              }

              if(this.right != null){
                  GTree<T> rightFind = this.right.find(data);
                  if(rightFind != null)
                      return rightFind;
              }

              return null;
          }
      
          public void insert(T data){
              if(this.left == null){
                  this.left = new GTree<T>(data);
              }
              
              else if(this.right == null){
                  this.right = new GTree<T>(data);
              }
              
              else{
                  int leftHeight = this.left.getHeight();
                  int rightHeight = this.right.getHeight();

                  if(leftHeight > rightHeight){
                      this.right.insert(data);
                  }
                  
                  else{
                      this.left.insert(data);
                  }
              }
          }
}

0
Comment
Question by:toymachiner62
  • 9
  • 4
13 Comments
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18853793
This is not an M-way tree, this is a binary tree with no rules for adding a child, well the only rule is: add the child in the subtree with minimal height. This makes the tree pretty much balanced, which is most likely what you want. Again, this is not an M-way tree.

You will have to keep a list of children at each node, so you can handle M children at every node, but maybe we can be of more use if you tell us which parts are required and which are not. Which methods are required specifically? insert? remove? find? traverse?

Mark
0
 
LVL 10

Accepted Solution

by:
ADSLMark earned 500 total points
ID: 18854369
Ok, I did some work already.. here is the adjusted M-tree, it consist of three files and I really did my best to make it very clear what everything does and make a elegant solution. Please download the graphviz toolkit, it really pays off to see a visualization of your tree, it's.... beautiful. :-)
Ok, here it comes:

/////////////////Example.java/////////////////
import java.io.File;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.util.Scanner;

/**
 * Example use of a GTree. It reads a file and transforms it into a GTree. The
 * first line of the file contains the maximum number of children for each
 * node, the second denotes the root, subsequent lines start with the value for
 * their node and are followed by the values for each child. These are then
 * defined on other lines.
 *
 * 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  ...
 * 29 4 9       ...
 */
public class Example
{
    /**
     * Program entry.
     *
     * @param   args    command line arguments
     */
    public static void main(String[] args)
        throws FileNotFoundException, ParseException
    {
        //Print usage
        if(args.length != 1)
        {
            System.out.println("Usage: java Example <file>");
            return;
        }

        //Parse file
        GTree<Integer> root = parseIntegerGTree(args[0]);

        //Visualize tree
        //new GTreeViz<Integer>().visualize("tree", root);
    }

    /**
     * Parses a file with the specified format and creates a GTree<Integer>
     * from it. It is necessary in the current implementation to have the
     * node be defined later than it's first use as child. In other words,
     * first define the parent, then the children, not the other way around.
     *
     * @param   filename                name of file to parse
     * @return                          the resulting GTree
     * @throws  FileNotFoundException   when the file could not be found
     * @throws  ParseException          when the file could not be parsed
     */
    public static GTree<Integer> parseIntegerGTree(String filename)
        throws FileNotFoundException, ParseException
    {
        Scanner sc = new Scanner(new File(filename));

        //Discard branching factor
        sc.nextInt();
        sc.nextLine();

        //Read root value
        GTree<Integer> root = new GTree<Integer>(sc.nextInt());
        sc.nextLine();

        //Read lines
        while(sc.hasNextLine())
        {
            Scanner sl = new Scanner(sc.nextLine());

            //Read node value and all children for that node
            int nodeValue = sl.nextInt();
            while(sl.hasNextInt())
            {
                GTree<Integer> child = new GTree<Integer>(sl.nextInt());
                root.insert(nodeValue, child);
            }
        }

        sc.close();

        //Return tree
        return root;
    }
}
/////////////////End/////////////////
/////////////////GTree.java/////////////////
import java.util.LinkedList;

/**
 * Implementation of an M-way tree. It uses a list to store the children for
 * a certain node. A child is again a subtree, so we can build bigger trees.
 * This value is the key of a node, so it needs to be comparable to be able
 * to do comparison on the key.
 */
public class GTree<T extends Comparable<? super T>>
{
    private LinkedList<GTree<T>> children;
    private T value;

    /**
     * Constructs a tree with a specific value and no children.
     *
     * @param   value   node value
     */
    public GTree(T value)
    {
        //Don't allow null values
        if(value == null)
            throw new NullPointerException("Null values not allowed!");

        //Initialize tree part
        this.children = new LinkedList<GTree<T>>();
        this.value = value;
    }

    /**
     * Returns a boolean signifying whether this value is in the tree, yes or no.
     *
     * @param   value       value of the node to search
     * @return  true if it's in the tree, otherwise false
     */
    public boolean contains(T value)
    {
        return (this.find(value) != null);
    }

    /**
     * Finds a child with a specific value in this tree.
     *
     * @param   value       value of the node to search
     * @return  null if it could not be found, otherwise the node with specified value
     */
    public GTree<T> find(T value)
    {
        //Found the value?
        if(this.value.equals(value))
            return this;

        //Recurse down all children and search
        for(GTree<T> child : this.children)
        {
            //Found child in subtree?
            GTree<T> result = child.find(value);
            if(result != null)
                return result;
        }

        //Not in this tree part
        return null;
    }

    /**
     * Returns the depth of the tree from this node.
     *
     * @return  value representing the depth
     */
    public int depth()
    {
        int max = 0;

        //Recurse down all children and pick the maximum
        for(GTree<T> child : this.children)
        {
            //Child depth bigger than current maximum?
            int depth = child.depth();
            if(depth > max || max < 0)
                max = depth;
        }

        //Increase by one to account for current node
        return max+1;
    }

    /**
     * Inserts a child in this tree at the node with a specific value.
     *
     * @param   value       value of the node where to insert this child
     * @param   newchild    child to add
     * @return  true if the insert was succesful, otherwise false
     */
    public boolean insert(T value, GTree<T> newchild)
    {
        //Are we at the correct node?
        if(this.value.equals(value))
        {
            this.children.add(newchild);
            return true;
        }

        //Recurse down all the children
        for(GTree<T> child : this.children)
        {
            //Did we insert the child?
            if(child.insert(value, newchild))
                return true;
        }

        //Not in this tree part
        return false;
    }

    /**
     * Removes a child from this tree.
     *
     * @param   oldchild    child to remove
     * @return  true if the remove was succesful, otherwise false
     */
    public boolean remove(GTree<T> oldchild)
    {
        //If it's a child of this node, then remove it
        if(this.children.contains(oldchild))
        {
            this.children.remove(oldchild);
            return true;
        }

        //Recurse down all the children
        for(GTree<T> child : this.children)
        {
            //Did we remove the child?
            if(child.remove(oldchild))
                return true;
        }

        //Not in this tree part
        return false;
    }

    /**
     * Sets the value of this node.
     *
     * @param   value   new value
     */
    public void setValue(T value)
    {
        this.value = value;
    }

    /**
     * Returns the value of this node.
     *
     * @return  value stored in this node
     */
    public T getValue()
    {
        return this.value;
    }

    /**
     * Returns all children of this node.
     *
     * @return  list of all children
     */
    public LinkedList<GTree<T>> getChildren()
    {
        return this.children;
    }
}
/////////////////End/////////////////
/////////////////GTreeViz.java/////////////////
import java.io.File;
import java.io.PrintWriter;
import java.io.IOException;

/**
 * Graphical visualization of a GTree using graphviz toolkit.
 */
public class GTreeViz<T extends Comparable<? super T>>
{
    /**
     * Visualizes a tree with the use of the graphviz toolkit.
     *
     * @param   filename    filename for the output file
     * @param   node        node from which to visualize the tree
     */
    public void visualize(String name, GTree<T> node)
    {
        PrintWriter pw = null;

        try
        {
            //Create ouput stream
            pw = new PrintWriter(new File(name+".dot"));
            pw.println("digraph G {");
            formatTree(pw, node);
            pw.println("}");
            pw.close();

            //Convert to PostScript
            Runtime.getRuntime().exec("dot -Tps -o"+name+".ps "+name+".dot");
        }
        catch(IOException ioe)
        {
            System.err.println(ioe);
        }
        finally
        {
            if(pw != null) pw.close();
        }
    }

    /**
     * Format a tree in DOT notation.
     *
     * @param   pw              PrintWriter to write to
     * @param   node            node from which to format the tree
     * @throws  IOException     when an error occured during writing
     */
    public void formatTree(PrintWriter pw, GTree<T> node)
        throws IOException
    {
        //Print edges from node to all children and recurse down all the children
        for(GTree<T> child : node.getChildren())
        {
            pw.println(node.getValue() + " -> " + child.getValue());
            formatTree(pw, child);
        }
    }
}
/////////////////End/////////////////

As you can see, I did not include the traversals. I think you should have another class which does a traversal, like an abstract class which defines how an traversal looks like, sth named:

GTreeTraversal with abstract methods like, hasNext(), next(), etc.

and then subclasses for the specific traversals, GTreePreOrderTraversal, GTreePostOrderTraversal, GTreeInOrderTraversal and GTreeLevelOrderTraversal. Anyway, it's getting late and I think you should do some work yourself aswell :-).

Have fun with the code,
Mark
0
 
LVL 2

Author Comment

by:toymachiner62
ID: 18860032
I couldn't figure out how to get that graphviz working. But anyways i'm not sure how to do a traversal for an m-way tree. i know for a binary tree you have do:
public void preOrderTraverse()
{
     System.out.println(node.getData());
     preOrderTraverse(node.getLeftChild());
     preOrderTraverse(node.getRightChild());
}
but for an m-way tree i tried to do
 public void preOrderTraverse(LinkedList<GTree<T>> node)
    {
          System.out.println(node.getValue());
          preOrderTraverse(node.getChildren());
    }
but i get an error that getValue and getChildren are undefined for the type LinkedList<GTree<T>>.
but the getChildren method looks like this

public LinkedList<GTree<T>> getChildren()
    {
        return this.children;
    }
 
so i don't understand how to do that for an m-way tree.
Also did i add my input file in the right place??

and i'm trying to write to a file in the same format as the file was read but i don't understand your whole file reading method. I'm not sure why you have two scanners.

i modified  this -->  GTree<Integer> root = parseIntegerGTree(args[0], args[0];  i'm not sure what the args[0] does. and it gave me an error there since i added 2 strings to the parseIntegerGTree. would that just have to be (args[0], args[0])?


public class Example
{
    /**
     * Program entry.
     *
     * @param   args    command line arguments
     */
    public static void main(String[] args)
        throws FileNotFoundException, ParseException
    {
        //Print usage
        if(args.length != 1)
        {
            System.out.println("Usage: java Example <file>");
            return;
        }

        //Parse file
        GTree<Integer> root = parseIntegerGTree(args[0], args[0]);             <-- I ALSO ADDED A PRINTWRITER AND IS THIS RIGHT TO HAVE THIS HERE?

        //Visualize tree
        new GTreeViz<Integer>().visualize("tree.dat", root);                     <--IS THIS RIGHT?
    }

    /**
     * Parses a file with the specified format and creates a GTree<Integer>
     * from it. It is necessary in the current implementation to have the
     * node be defined later than it's first use as child. In other words,
     * first define the parent, then the children, not the other way around.
     *
     * @param   filename                name of file to parse
     * @return                          the resulting GTree
     * @throws  FileNotFoundException   when the file could not be found
     * @throws  ParseException          when the file could not be parsed
     */
    public static GTree<Integer> parseIntegerGTree(String readFromFile, String writeToFile)
        throws FileNotFoundException, ParseException
    {
          readFromFile = "tree.dat";
          Scanner sc = null;
        sc = new Scanner(new File(readFromFile));
       
        writeToFile = "output.dat";
        PrintWriter writeFile = null;
        writeFile = new PrintWriter(writeToFile);

        //Discard branching factor
        sc.nextInt();
        sc.nextLine();

        //Read root value
        GTree<Integer> root = new GTree<Integer>(sc.nextInt());
        sc.nextLine();
               
       
        //Read lines
        while(sc.hasNextLine())
        {
            Scanner sl = new Scanner(sc.nextLine());

            //Read node value and all children for that node
            int nodeValue = sl.nextInt();
            while(sl.hasNextInt())
            {
                GTree<Integer> child = new GTree<Integer>(sl.nextInt());
                root.insert(nodeValue, child);
            }
        }

        sc.close();

        //Return tree
        return root;
    }
}
/////////////////End/////////////////
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18860977
First some answers:
- Traversal is different for an M-way tree yes.
- Two scanners, one for the whole file and the other for the line, there are other solutions, but this one looked pretty nice.
- Graphviz, just install from the website (not sure which platform your on) and make sure you can execute the program: "dot" from the command line (on Windows: Start > Run > cmd > dot
- args[0] is the first element on the command line, so args[1] is the second.. etc. don't forget to check whether the args array is big enough
- Writing the format to a file again.
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18860993
Whoops, hit the button accidentally.
- Writing the format to a file again can indeed be done with a printwriter. Just take the root and write the root to a line, then pick all it's children and recursively write these to a file. That's basically the idea.

If i have time I might be able to give you some code also.. but maybe you would like to try it yourself first. Just take a good look at my code and make sure you understand why I wrote what i wrote. It's not difficult to understand, you only need to know how a for-loop works.

Mark
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18861062
Ah, even smarter solution for writing the file is to do a level-order traversal and write the parent+children to a line. This is probably sounding like *what?!?*...

Mark
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 10

Expert Comment

by:ADSLMark
ID: 18861239
Ok, here are the traversals:

    /**
     * Pre-order traversal of this tree.
     */
    public void preOrderTraversal()
    {
        //Print this node
        System.out.print(this.value+" ");

        //Recurse down all the children
        for(GTree<T> child : this.children)
            child.preOrderTraversal();
    }

    /**
     * Post-order traversal of this tree.
     */
    public void postOrderTraversal()
    {
        //Recurse down all the children
        for(GTree<T> child : this.children)
            child.postOrderTraversal();

        //All children done, now print this node
        System.out.print(this.value+" ");
    }

    /**
     * Level-order traversal of this tree.
     */
    public void levelOrderTraversal()
    {
        //Keep track of the level with a queue
        LinkedList<GTree<T>> queue = new LinkedList<GTree<T>>();
        queue.add(this);

        //While the queue has elements, try to add more to the queue
        while(queue.size() > 0)
        {
            GTree<T> node = queue.removeFirst();
            System.out.print(node.value+" ");
            queue.addAll(node.getChildren());
        }
    }


and also an additional method for determining the branching factor, which you need to write the tree to file:

    /**
     * Returns the maximum branching factor of the tree from this node.
     *
     * @return  integer representing the maximum branching factor
     */
    public int branchFactor()
    {
        int max = this.children.size();

        //Recurse down all children and pick the maximum
        for(GTree<T> child : this.children)
        {
            //Child depth bigger than current maximum?
            int branchFactor = child.branchFactor();
            if(branchFactor > max)
                max = branchFactor;
        }

        //Return the maximum
        return max;
    }

Mark
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18861311
And here is your write to file:

    /**
     * Writes a tree to a file with the specified format.
     *
     * @param   filename        name of file to write to
     * @return  root            the GTree to write
     * @throws  IOException     when the file could not be written
     */
    public static void writeIntegerGTree(String filename, GTree<Integer> root)
        throws IOException
    {
        PrintWriter pw = new PrintWriter(new File(filename));

        //Write branching factor
        pw.println(root.branchFactor());

        //Write root value
        pw.println(root.getValue());

        //Perform level-order traversal to write each node to a line
        LinkedList<GTree<Integer>> queue = new LinkedList<GTree<Integer>>();
        queue.add(root);

        //Write a line each iteration
        while(queue.size() > 0)
        {
            GTree<Integer> node = queue.removeFirst();
            LinkedList<GTree<Integer>> children = node.getChildren();

            //Only write for nodes with one or more children
            if(children.size() > 0)
            {
                pw.print(node.getValue());
                for(GTree<Integer> child : children)
                    pw.print(" " + child.getValue());
                pw.println();
            }

            //Enqueue all the children for upcoming lines
            queue.addAll(node.getChildren());
        }

        pw.close();
    }

Mark

PS: I'm wondering if it might not be easier to add this to the GTree class, but then again, it makes the GTree class kinda *big*, anyway, I'm not sure what you want to do with it.. so i guess this is fine.
0
 
LVL 2

Author Comment

by:toymachiner62
ID: 18873926
Only one more thing is how to actually construct the tree from the file? I started messing with this and i can insert a root node but i'm having trouble inserting the children into a parent node. Any help in constructing the tree from the file?

This is what i did to create a root node      GTree rootNode = new GTree (101);

If i try to create a child like this it doesn't work.

GTree rootNode = new GTree (101);
       
        GTree child = new GTree(2);
       
        rootNode.insert(101, child);
       
        System.out.println(rootNode.getValue());
        System.out.println(child.getChildren());







package Test;

/////////////////Example.java/////////////////
import java.io.*;
import java.text.ParseException;
import java.util.LinkedList;
import java.util.Scanner;

/**
 * Example use of a GTree. It reads a file and transforms it into a GTree. The
 * first line of the file contains the maximum number of children for each
 * node, the second denotes the root, subsequent lines start with the value for
 * their node and are followed by the values for each child. These are then
 * defined on other lines.
 *
 * 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  ...
 * 29 4 9       ...
 */
public class Example
{
    /**
     * Program entry.
     *
     * @param   args    command line arguments
     * @throws IOException
     */
    public static void main(String[] args)
        throws ParseException, IOException, FileNotFoundException
    {
          
          
          
       
        String fileName = "tree.dat";
        Scanner sc = new Scanner(new File(fileName));

        //Discard branching factor
        sc.nextInt();
        sc.nextLine();

        //Read root value
        GTree<Integer> root = new GTree<Integer>(sc.nextInt());
        sc.nextLine();

        //Read lines
        while(sc.hasNextLine())
        {
            Scanner sl = new Scanner(sc.nextLine());

            //Read node value and all children for that node
            int nodeValue = sl.nextInt();
            while(sl.hasNextInt())
            {
                GTree<Integer> child = new GTree<Integer>(sl.nextInt());
                root.insert(nodeValue, child);
            }
        }
       
       
        GTree rootNode = new GTree (101);
       
        GTree child = new GTree(2);
       
        rootNode.insert(101, child);
       
        System.out.println(rootNode.getValue());
        System.out.println(child.getChildren());
       
       
       
       
       
       
        GTree<Integer> yea = new GTree<Integer>(100);
            Integer value = 22;
            yea.insert(value, yea);
       
        //writes the tree to a file
        writeIntegerGTree(root);
       
        //closes the input file
        sc.close();
    }

   
   

/**
 * Writes a tree to a file with the specified format.
 *
 * @param   filename        name of file to write to
 * @return  root            the GTree to write
 * @throws  IOException     when the file could not be written
 */

public static void writeIntegerGTree(GTree<Integer> root)
    throws IOException
{
      
    PrintWriter pw = new PrintWriter(new FileWriter("output.dat"));

    //Write branching factor
    pw.println(root.branchFactor());

    //Write root value
    pw.println(root.getValue());

    //Perform level-order traversal to write each node to a line
    LinkedList<GTree<Integer>> queue = new LinkedList<GTree<Integer>>();
    queue.add(root);

    //Write a line each iteration
    while(queue.size() > 0)
    {
        GTree<Integer> node = queue.removeFirst();
        LinkedList<GTree<Integer>> children = node.getChildren();

        //Only write for nodes with one or more children
        if(children.size() > 0)
        {
            pw.print(node.getValue());
            for(GTree<Integer> child : children)
                pw.print(" " + child.getValue());
            pw.println();
        }

        //Enqueue all the children for upcoming lines
        queue.addAll(node.getChildren());
    }

    pw.close();
      }
}
0
 
LVL 2

Author Comment

by:toymachiner62
ID: 18874084
Basically i'm just wondering how to insert a child into a node
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18874349
You are showing the results incorrect.

        //Construct tree
        GTree<Integer> rootNode = new GTree<Integer>(101);
        GTree<Integer> aNode = new GTree<Integer>(2);
        rootNode.insert(101, aNode);

        //Print result
        System.out.println(rootNode.getValue());
        for(GTree<Integer> child : rootNode.getChildren())
            System.out.println(child.getValue());

You should print the children of the 'rootNode', not the children of the child (since that node has none).

Mark
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18874353
insert(T pValue, GTree<T> pNode)

basically means.. find the node with value 'pValue' and if you do, then make 'pNode' a child of this node.
0
 
LVL 2

Author Comment

by:toymachiner62
ID: 18874385
Oh ok so i was just printing it wrong. thatnk you very much for all your help. The teacher of my class refuses to help us with code, only concepts but he's not even very good at that. Thank you for all your help.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now