Click here to Skip to main content
16,017,623 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hello I have got this  tree data structure implementation in java ,
however the problem I am facing is that somehow the add method does
seem to me that it is not working properly .
When I for example use  " public void CreateFromDefinition(String definition) "
and put in for example  " (A(B(E(K),F),C(G(L,M)),D(H,I(N),J))) " , then when I use
System.out.println(y.GetListDefinition());
then what I get for the output is  =

                         name : (A
                         Exception in thread "main" java.lang.NullPointerException
                     at ads2.ADS2Tree.CreateFromDefinition(ADS2Tree.java:72)
                     at ads2.Main.main(Main.java:90)
                         Java Result: 1




Can anybody please help me solve this problem ?

Thank you

------------------------------

Here is the code for the tree and node -

Code for the tree :



package ads2;

  /*
   * This class defines the top-level tree data structure.
  */


public class ADS2Tree
{
  // Default Constructor
  public ADS2Tree()
  {
  }
  
  // -------------
public ADS2TreeNode leftNode() 
{return root.left;}

public ADS2TreeNode rightNode() {return root.right;}

public static int getNodeValue() 
{
    return ADS2TreeNode.nodeValue;

}

  private ADS2TreeNode root;    
  
  
  // Takes a string input of a list structure that defines a tree
  // e.g. definition="(A(B(E(K),F),C(G(L,M)),D(H,I(N),J)))");
  // and sets up the internal tree structure to represent this structure
  // Any previous tree structure is overridden when this method is called
  public void CreateFromDefinition(String definition)
  {     
      int startofname = 0;
      ADS2TreeNode current = new ADS2TreeNode (definition) ; // "dummy"
      root = current ;
      
      //TreeNode current = null;
      for (int i = 0; i<definition.length(); i++)
      {   
          char val = definition .charAt(i);
          if ( val == '(' || val == ')' || val == ',')
          {
              if (startofname != i)
              {
                  String name = definition.substring(startofname,i);
                  System.out.println("name : " + name);
                  
                  ADS2TreeNode node = new ADS2TreeNode (name);
                  current.AddChild(node);
                  if (val == '(')
                  {
                    current = node ;
                  }
                  else if (val == ')')
                  {    
                        current = current.GetParent();
                  }
              
                  startofname = i + 1;
                  
              }
              
              root = root.GetChild(0);
              
              // current = current ;
          }
      }
      
  }
  
  // Returns a String containing the list format of the tree in the following format:
  // NodeName(Child1,Child2,...Childn)
  // For example: (A(B(E(K),F),C(G(L,M)),D(H,I(N),J)))
  public String GetListDefinition()
  {
          return "(" + root.toString() + " ) " ;
  //  return "Implement list output of this tree, for example: (A(B(E(K),F),C(G(L,M)),D(H,I(N),J)))";
  }

  // Returns a String contain the pre-order enumation of the tree data structure
  // The return type should just contain the name of the treenodes, separated by commas
  // For example: A,B,C,D,E,F,G

  
  public String GetPreOrder(ADS2TreeNode root) 
  {
      
      
  GetPreOrder(root.left);  
  GetPreOrder(root.right);  
  
		if (root == null)
			return "";

		String result = root.data;
		if (root.left != null)
			result += GetPreOrder(root.left);
		if (root.right != null)
			result += GetPreOrder(root.right);
		return result;

  
  }
  

  public String GetInOrder()
  {
    return null;
  }
  
  public String GetPostOrder()
  {    		      if (root == null)
			return "";

		String result = "";
		if (root.left != null)
			result += GetPreOrder(root.left);
		if (root.right != null)
			result += GetPreOrder(root.right);
		result += root.data;
		return result;
                          
  }

  
 private void GetBreadthFirstOrder(ADS2TreeNode root) 
  {
         GetBreadthFirstOrder(root);
  }
      

  public String GetBreadthFirstOrder() 
  {
      
     if (root == null)
          return root.GetData();
     
          System.out.print(root.data + " ");
      GetBreadthFirstOrder(root.left);
      GetBreadthFirstOrder(root.right);
    
    return null;
    
  }
  

  public int GetTreeDegree()
  {
    return GetTreeHeight(root);
  }
  

  public int GetTreeHeight()
  {  
     if (root==null)
     return 0;
    int x = GetTreeHeight(root.left);
    int y = GetTreeHeight(root.right);
    return (x>y?x:y)+1;
    
  }
  
  
     public int GetTreeNodeCount()
   {
      return GetTreeNodeCount(root);
   }
   private int GetTreeNodeCount(ADS2TreeNode p)
   {
      if(p == null) return 0;
      else
      if(p.left == null && p.right == null) return 1;
      else
      return GetTreeNodeCount(p.left) + GetTreeNodeCount(p.right);
   }

  public String toString()
  {
    return super.toString();
  }

    private int GetTreeHeight(ADS2TreeNode left) {
        throw new UnsupportedOperationException("Not supported yet."); 
    }


  
}





// --------------------------------------------------------


Here is the code for node :



package ads2;


public class ADS2TreeNode
{

  public String data;     // data about this node
  private ADS2TreeNode parent; // parent node
  public ADS2TreeNode child[];
  public int noOfChildren;
  private final int maxChildren = 10;
  // add in variables to hold one or more child nodes
  
  public ADS2TreeNode right; // right node
  public ADS2TreeNode left;
  public static int nodeValue;
  public ADS2TreeNode p;
  
   // Add required constructors
   public ADS2TreeNode()
   {
     child = new ADS2TreeNode[maxChildren];
     noOfChildren = 0;
   }

   public ADS2TreeNode(String definition) {  
       child = new ADS2TreeNode[maxChildren];
       noOfChildren = 0;
       data = definition;  
   }
  
  public String GetData()
  {
    return data;
  }
   
  public void SetData(String data)
  {
    this.data=data;
  }

  // returns the number of children this node has 
  public int GetNoOfChildren()
  {
      return noOfChildren;
  }
  
  public String toString()
  {
      
      String res = data;
      if ( noOfChildren != 0)
      {
     
      res += " ( " + child[0];
      for ( int i = 1; i < noOfChildren; i++)
          res+= "," + child[i];
      res+= ")";
           
       }
  
     return res; 
  }

    void AddChild(ADS2TreeNode node) 
    {
        // Checking whether there is enough space
        if(noOfChildren < maxChildren) {
            // Can add child
            node.parent = this;
            child[noOfChildren] = node;
            noOfChildren++;
        }
        // else { cannot add child } 
    }

    ADS2TreeNode GetParent() {
        return parent;
    }

    ADS2TreeNode GetChild(int i) {
         return child[i];
    }
    
    
}
Posted
Updated 24-Jan-15 8:56am
v2
Comments
Sergey Alexandrovich Kryukov 24-Jan-15 15:49pm    
And the question is?... what's the problem? You need to explain what did you try to achieve and how, what did you want to observe and what you got, and why do you feel it's wrong...
—SA

1 solution

First problem is that you set the root to null and try to use that;
root = root.GetChild(0);

You need to make sure you don't keep processing after root is null. One way might be by fixing the for-loop;
for (int i = 0; i<definition.length() && root != null; i++)


But even then, as you let root change inside CreateFromDefinition it will still be null when the method completes, and since GetListDefinition calls root.toString() it will fail.

You'll want to make sure the root member always points to the root, a lazy way of achieving this would be to set root to the initial node created;
int startofname = 0;
ADS2TreeNode current = new ADS2TreeNode (definition) ; // "dummy"
root = current ;
ADS2TreeNode r = current;

then, at the end of that method, set root=r;.

Hope this helps,
Fredrik
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900