user3639901
user3639901

Reputation: 11

create generic tree with more than two child each may have unique proprties

I have to create a generic tree. It may have more than 2 children, and one child may act as a parent for the next level and another may not.(Not binary tree) I have tried using the below code. The problem is, they are created by assuming all children may act as a parent.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


class Tree<T>
{
private T data;
private Tree<T> parent;
private List<Tree<T>> children;

public Tree(T data)
{
    this.data = data;
    children = new ArrayList<Tree<T>>();
}

/**
 * Adds a new child node to the parent node returns the added Child
 */
public Tree<T> addChild(T childData)
{
    Tree<T> childNode = new Tree<T>(childData);
    childNode.parent = this;
    this.children.add(childNode);
    return childNode;
}



/**
 * Returns the parent
 */
public Tree<T> getRoot()
{
    if (this == null)
    {
        return this;
    }

    Tree<T> parentTmp = this.parent;
    Tree<T> root = this;

    //iteration
    while (parentTmp != null)
    {
        parentTmp = root.parent;
        if (parentTmp != null)
        {
            root = parentTmp;
        }

    }

    return root;
}


@Override
public String toString()
{
    StringBuilder output = new StringBuilder("[");
    helpToString(this, output, 0);
    output.append("]");
    return output.toString();
}

private void helpToString(Tree<T> tree, StringBuilder output, int level)
{
    if (tree == null)
        return; // Tree is empty, so leave.

    output.append(getSpaces(level) + tree.data);

    List<Tree<T>> children2 = tree.children;
    ++level; //increment the level

    Iterator<Tree<T>> iterator = children2.iterator();
    while (children2 != null && iterator.hasNext())
    {
        Tree<T> next = iterator.next();
        if (next != null)
        {
            helpToString(next, output, level); //recursion
        }

    }

}

private String getSpaces(int level)
{
    StringBuilder sb = new StringBuilder("\n");
    for (int i = 0; i < level; i++)
    {
        sb.append("--");
    }

    return sb.toString();
}

 }

public class TreeTest
{
public static void main(String[] args)
{
    Tree<String> root = new Tree<String>("A");
    root.addChild("B");
    Tree<String> childC = root.addChild("C");
    root.addChild("D");

    Tree<String> childC1 = childC.addChild("C1");

    System.out.println("root = " + childC.getRoot());                 // toString() method is invoked
                // toString() method is invoked

}

}

Output:

root = [
A
--B
--C
----C1
--D]

Here A is root having 3 children b,c,d, C is Parent for C1. For my scenario B having 2 properties, description and value, is that has to be hash map, and C having 1 properties description , so it has to be arraylist.

A[Description]
--B[Description,Value]
--C[Description]
----C1[Description,Value]
--D[Description,Value]]

So I have to create a generic tree that must have arraylist and hashmap.

Root[Description: root]
 -SubPart1[Description: SubPart1]
    ---- Description: SubPart1.1 and Value: 1.1 
    ---- Description: SubPart1.2 and Value: 1.2
- Description: Root 1.1 and Value: 1.1
- Description: Root 1.2 and Value: 1.2
- Description: Root 1.3 and Value: 1.3
-SubPart2[Description: SubPart2]
    ---- Description: SubPart2.1 and Value:2.1 
    ---- Description: SubPart2.2 and Value: 2.2
    ---- Description: SubPart2.3 and Value: 2.3
- Description: Root 1.4 and Value: 1.4
-SubPart3[Description: SubPart3]
    ---- Description: SubPart3.1 and Value:3.1 

Upvotes: 0

Views: 3857

Answers (1)

Kenneth Clark
Kenneth Clark

Reputation: 1755

Here is an example of what you are looking for

Tree Class

public class Tree
{
  private String description = null;
  private ArrayList<Tree> treeList = new ArrayList<Tree>();
  private HashMap<Integer,Tree> childrenTreeList = new HashMap<Integer,Tree>();
  private int value = 0;

  public Tree(String description, int value)
  {
    this.description = description;
    this.value = value;
  }

  public String getDescription()
  {
    return description;
  }

  public void setDescription(String description)
  {
    this.description = description;
  }

  public int getValue()
  {
    return value;
  }

  public void setValue(int value)
  {
    this.value = value;
  }

  public void addChildTree(Tree childTree, int value)
  {
    this.childrenTreeList.put(value, childTree);
  }

  public void addTree(Tree tree)
  {
    this.treeList.add(tree);
  }

  public ArrayList<Tree> getTreeList()
  {
    return treeList;
  }

  public HashMap<Integer, Tree> getChildrenTreeList()
  {
    return childrenTreeList;
  }
}

Main Test

public class TreeRunner
{

  public static void main(String[] args)
  {
    Tree root = new Tree("Root", 1);

    // Child B
    Tree treeB = new Tree("SubPart1", 1);
    treeB.addChildTree(new Tree("SubPart1", 1),1);
    treeB.addChildTree(new Tree("SubPart1", 2),2);
    root.addTree(treeB);

    root.addChildTree(new Tree("Root", 1),1);
    root.addChildTree(new Tree("Root", 2),2);
    root.addChildTree(new Tree("Root", 3),3);
    root.addChildTree(new Tree("Root", 4),4);

    // Child D
    Tree treeD = new Tree("SubPart2", 2);
    treeD.addChildTree(new Tree("SubPart2", 1),1);
    treeD.addChildTree(new Tree("SubPart2", 2),2);
    treeD.addChildTree(new Tree("SubPart2", 3),3);
    root.addTree(treeD);

    // Child D
    Tree treeE = new Tree("SubPart3", 3);
    treeE.addChildTree(new Tree("SubPart3", 1),1);
    root.addTree(treeE);

    System.out.println(String.format("Root[Description: %s]",root.getDescription()));
    for (Map.Entry<Integer, Tree> treeEntry : root.getChildrenTreeList().entrySet())
    {
      System.out.println(String.format("-------- Description: %s %d.%d and Value %d.%d",root.getDescription(),root.getValue(),treeEntry.getKey(),root.getValue(),treeEntry.getValue().getValue()));
    }
    for (Tree treeObj : root.getTreeList())
    {
      System.out.println(String.format("%s[Description: %s]",treeObj.getDescription(),treeObj.getDescription()));
      HashMap<Integer, Tree> treeMap = treeObj.getChildrenTreeList();
      for (Map.Entry<Integer, Tree> treeEntry : treeMap.entrySet())
      {
        System.out.println(String.format("-------- Description: %s %d.%d and Value %d.%d",treeObj.getDescription(),treeObj.getValue(),treeEntry.getKey(),treeObj.getValue(),treeEntry.getValue().getValue()));
      }
    }
  }
}

Output

Root[Description: Root]
-------- Description: Root 1.1 and Value 1.1
-------- Description: Root 1.2 and Value 1.2
-------- Description: Root 1.3 and Value 1.3
-------- Description: Root 1.4 and Value 1.4
SubPart1[Description: SubPart1]
-------- Description: SubPart1 1.1 and Value 1.1
-------- Description: SubPart1 1.2 and Value 1.2
SubPart2[Description: SubPart2]
-------- Description: SubPart2 2.1 and Value 2.1
-------- Description: SubPart2 2.2 and Value 2.2
-------- Description: SubPart2 2.3 and Value 2.3
SubPart3[Description: SubPart3]
-------- Description: SubPart3 3.1 and Value 3.1

You will have to implement a further Ordering to get a VERY specific order As you can see in your example You print roots children after SubPart1

Upvotes: 1

Related Questions