Stats

Tuesday, 30 December 2014

How to implement tree in java?

Steps
1. Create class Node with generic parameter T and having instance variables as
     1.1 data of type T i.e. T data;
     1.2 List of Node of Type T i.e. List<Node<T>> children;
     1.3 parent of type Node<T> i.e. Node<T> parent;
   & methods as
     Constuctors as
      public Node(T data)
     {
            this.data = data;
      }
      public Node(T data,Node<T> parent)
      {
           this.data = data;
           this.parent = parent;
       }
       Add methods to getChildren, addChild, setParent.
2. Create class Tree with instance variables as
     2.1 root with type Node<T> i.e. Node<T>root;
3. Create Class TestTree with main method.
    Create a local variable t of type Tree.
    Add root and other nodes inside the tree.

Thanks,
Sagar

2 comments: