Please someone help!!i m a newbie in Java. i want to make a tree structure from an Array List. My input is
1.1
1.2
1.3
1.3.1.1
1.3.1.2
1.4
1.4.1.1
1.4.2.1
and my aim is to get a Tree like
1.1
1.2
1.3
1.4 1.3.1.1
1.4.1.1 1.5 1.3.1.2
1.4.1.2
and so on.
Please find below my classes for the same. I get a nullPoniter at test.tree.Node.addChild(Node.java:28) and I know it is because the 'children' is null but I dont know how to set the children for the first time. Please Help... :(
public class Tree {
private Node root;
public Tree(String rootData)
{
root=new Node();
root.data=rootData;
root.children=new ArrayList<Node>();
}
public Tree() {
super();
}
public Node getRoot(){
return this.root;
}
public void setRoot(Node rootElement) {
this.root = rootElement;
}
}
and Node class
class Node {
String data;
Node parent;
List<Node> children;
public Node() {
super();
}
public Node(String name)
{
super();
this.data=name;
}
public void addChild(String name) {
this.addChild(new Node(name));
}
public void addChild(Node child) {
this.children.add(child);
}
public void removeChild(Node child) {
this.children.remove(child);
}
public void removeChild(String name) {
this.removeChild(this.getChild(name));
}
public Node getChild(int childIndex) {
return this.children.get(childIndex);
}
public Node getChild(String childName) {
for (Node child : this.children) {
if (child.data.equals(childName)) { return child; }
}
return null;
}
public List<Node> getChildren() {
if (this.children == null) {
return new ArrayList<Node>();
}
return this.children;
}
public void setChildren(List<Node> children) {
this.children = children;
}
public Node getParentNode() {
return this.parent;
}
}
and the Test class is
public class TreeTest {
public static void main(String[] args) {
TreeTest tt = new TreeTest();
ArrayList<String> newArr= new ArrayList<String>();
newArr.add("1.1");
newArr.add("1.2");
newArr.add("1.3");
newArr.add("1.3.1.1");
newArr.add("1.3.1.2");
newArr.add("1.4");
newArr.add("1.4.1.1");
newArr.add("1.4.2.1");
int lCount=0;
int maxCount= newArr.size();
Tree tr= new Tree();
Node rootNode = new Node();
String parent_name=null;
Node currentNode= new Node();
for(String line: newArr){
if(lCount==0){
rootNode = tt.getTree(line);
tr.setRoot(rootNode);
currentNode= rootNode;
}
else{
List<Integer> cur = new ArrayList<Integer>();
List<Integer> pre = new ArrayList<Integer>();
cur= tokenize(line);
pre= tokenize(newArr.get(lCount-1));
if(cur.size()==pre.size()){
currentNode.addChild(tt.getTree(line));
currentNode= tt.getTree(line);
}
else if (cur.size()>pre.size()){
currentNode.addChild(tt.getTree(line));
parent_name= newArr.get(lCount-1);
currentNode= tt.getTree(line);
}
else if(cur.size()< pre.size()){
currentNode= tt.getTree(parent_name);
currentNode.addChild(tt.getTree(line));
currentNode= tt.getTree(line);
}
}
lCount++;
}
}
private Node getTree(String string) {
// TODO Auto-generated method stub
Node rootNode = new Node(string);
return rootNode;
}
private static List<Integer> tokenize(String line) {
// TODO Auto-generated method stub
List<Integer> line_Arr = new ArrayList<Integer>();
String[] tokens = line.split("\\.");
int i=0;
for(String atr: tokens)
line_Arr.add(Integer.parseInt(atr));
return line_Arr;
}
}
In both constructors of your Node class, add this statement after the super call: -
children = new ArrayList<Node>();
This will instantiate your List children.
public Node() {
super();
this.children = new ArrayList<Node>();
}
public Node(String name)
{
super();
this.children = new ArrayList<Node>();
this.data=name;
}
Also, you can change your 1-arg and 0-arg Tree constructor from: -
public Tree(String rootData)
{
root=new Node();
root.data=rootData;
root.children=new ArrayList<Node>();
}
public Tree() {
super();
}
to the below one, that will instantiate the Node using the parameterized constructor: -
public Tree(String rootData) {
root=new Node(rootData);
}
public Tree() {
root = new Node();
}
P.S: -
You don't need to add super() call explicitly, if you only want to invoke the super class 0-arg constructor. Compiler adds this call by default.
Related
I am writing a code to practice some linked list example with basics but came across a problem when in linked list class in voidadd method what does it means when I pass the Node variable that is "top" inside the node objects ? does it help it to point the previous data? i have indicated the part that refers to my question
public class Node
{
private int data;
private Node nextNode;
public Node(int dataP , Node nextNodeP)
{
data = dataP;nextNode = nextNodeP;
}
public int getData()
{
return data;
}
public Node getNextNode()
{
return nextNode;
}
public void setData(int newData) //to replace the value of some notes [12| ] --> [120| ]
{
data = newData;
}
public void setNext(Node newNextNode) // pointing to top ---> [120| ] ---> [last | null]
{
nextNode = newNextNode;
}
}
public class LinkedList {
private Node top;
private int size;
public LinkedList() {
top = null;
size = 0;
}
public int getSize() {
return size;
}
public void addNode(int newData) {
Node temp = new Node(newData, top); //question
top = temp; //points to the same
size++;
}
}
Define a node at its own class.
Here is a simple example :
public class LinkedList {
private Node first,last;
private int size ;
//adds node as last. not null safe
public void addNode(Node node) {
if(first == null) {
node.setParent(null);
first = node;
last = node;
}else {
node.setParent(last);
last = node;
}
size++;
}
public Node getFirst() {return first;}
public Node getLast() { return last; }
public int getSize() {return size;}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.addNode(new Node(0,null));
list.addNode(new Node(1,null));
list.addNode(new Node(2,null));
list.addNode(new Node(3,null));
Node node = list.getLast();
System.out.println("list has "+ list.size + " nodes:");
while(node != null) {
System.out.println(node);
node = node.getParent();
}
}
}
class Node{
private int data;
private Node parent;
Node(int nodeData, Node parent) {
data = nodeData;
this.parent = parent;
}
public int getData() { return data;}
public void setData(int data) { this.data = data; }
public Node getParent() {return parent; }
public void setParent(Node parent) {this.parent = parent;}
#Override
public String toString() {return "Node "+getData() +" parent:"+ getParent();}
}
In Java how to simplify using multilevel nested static class, in delcaration statements( like LinkedList.Node in below code), when creating objects in outerclass ?
I want to use something like "import static" statement so that I can avoid using long declaration statements. Please suggest.
I tried import statement like "import static LinkedListTechniques.LinkedList.*". But it is showing error - "The import LinkedListTechniques cannot be resolved".
public class LinkedListTechniques {
public static class LinkedList {
private Node head;
public static class Node {
private Node next;
private int value;
public Node() {
this.next = null;
this.value = -1;
}
public Node(int value, Node next) {
this.next = next;
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
public LinkedList() {
super();
// TODO Auto-generated constructor stub
}
public LinkedList(Node head) {
super();
this.head = head;
}
public Node getHead() {
return head;
}
public void setHead(Node head) {
this.head = head;
}
}
public static void insertAtEnd(LinkedList list, int element) {
if (list.getHead() == null) {
list.setHead(new LinkedList.Node(element, null));
return;
}
LinkedList.Node current = list.getHead();
while (current.next != null) {
current = current.next;
}
LinkedList.Node newNode = new LinkedList.Node(element, null);
current.next = newNode;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
Is your class LinkedListTechniques in the default package? If this is the case it won't be possible to use static import. Try to move it to a package and you'll be able to do what you want.
For example, I created a package example and created these classes inside:
LinkedListTechniques.java
package example;
public class LinkedListTechniques {
public static class LinkedList {
public static class Node {}
}
}
Main.java
package example;
import example.LinkedListTechniques.LinkedList.Node;
public class Main {
public static void main(String[] args) {
Node node = new Node();
}
}
and it compiled without errors.
So I¨m building a small game in which I want a search tree with all the possible moves. I¨m having some difficulties implementing the search tree however. I have managed to build a function that can calculate the move but then I¨m not sure how to build the tree, it should be recursivly. Each node should have a list with all possible moves.
public class Tree {
private Node root;
private int level;
public Tree(int level, Board board) {
this.level = level;
root = new Node(board);
}
public void add(Board board) {
int newLevel = board.numberPlacedDiscs();
if(newLevel>level){
//Add this at a new level.
Node newNode =new Node(board);
newNode.setParent(root);
root = newNode;
}else{
//add at this level.
root.addChild(new Node(board));
}
}
}
public class Tree {
private Node root;
private int level;
public Tree(int level, Board board) {
this.level = level;
root = new Node(board);
}
public void add(Board board) {
int newLevel = board.numberPlacedDiscs();
if(newLevel>level){
//Add this at a new level.
Node newNode =new Node(board);
newNode.setParent(root);
root = newNode;
}else{
//add at this level.
root.addChild(new Node(board));
}
}
}
As you can see I don't know how to add new Nodes. How do I know when to go down a level in the tree and add more nodes? Everytime a new disc is added to the board it should go down one level.
Here is a generic tree in Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TreeTest {
public static void main(String[] args) {
Tree tree = new Tree("root");
tree.root.addChild(new Node("child 1"));
tree.root.addChild(new Node("child 2"));
tree.root.getChild("child 1").addChild("child 1-1");
tree.root.getChild("child 1").addChild("child 1-2");
/*
root
-- child 1
---- child 1-1
---- child 1-2
-- child 2
*/
}
private static class Tree {
private Node root;
Tree(String rootData) {
root = new Node();
root.data = rootData;
root.children = new ArrayList<>();
}
public List<Node> getPathToNode(Node node) {
Node currentNode = node;
List<Node> reversePath = new ArrayList<>();
reversePath.add(node);
while (!(this.root.equals(currentNode))) {
currentNode = currentNode.getParentNode();
reversePath.add(currentNode);
}
Collections.reverse(reversePath);
return reversePath;
}
}
static class Node {
String data;
Node parent;
List<Node> children;
Node() {
data = null;
children = null;
parent = null;
}
Node(String name) {
this.data = name;
this.children = new ArrayList<>();
}
void addChild(String name) {
this.addChild(new Node(name));
}
void addChild(Node child) {
this.children.add(child);
}
void removeChild(Node child) {
this.children.remove(child);
}
public void removeChild(String name) {
this.removeChild(this.getChild(name));
}
public Node getChild(int childIndex) {
return this.children.get(childIndex);
}
Node getChild(String childName) {
for (Node child : this.children) {
if (child.data.equals(childName)) {
return child;
}
}
return null;
}
Node getParentNode() {
return this.parent;
}
}
}
blog post about generic tree data structure in java
Hope it helps
You can use this method to insert a Node into your tree:
private void insertNode(Node root, Node oldNode, Node newNode) {
if(root == null) {
return;
}
if(root == oldNode) {
oldNode.addChild(newNode);
return;
}
for(Node child : root.getChildren()) {
insertNode(child, oldNode, newNode);
}
}
So this method takes three parameters:
root - this is the root node of your tree.
oldNode - the node where you want to insert your newNode.
newNode - this is the node you want to be added to the children of your oldNode.
Node that if you pass a Node that does not exist in your tree, it will not throw any error. But you can modify to do it if you want.
My Tree/Node Class:
import java.util.ArrayList;
import java.util.List;
public class Node<T> {
private T data;
private List<Node<T>> children;
private Node<T> parent;
public Node(T data) {
this.data = data;
this.children = new ArrayList<Node<T>>();
}
public Node(Node<T> node) {
this.data = (T) node.getData();
children = new ArrayList<Node<T>>();
}
public void addChild(Node<T> child) {
child.setParent(this);
children.add(child);
}
public T getData() {
return this.data;
}
public void setData(T data) {
this.data = data;
}
public Node<T> getParent() {
return this.parent;
}
public void setParent(Node<T> parent) {
this.parent = parent;
}
public List<Node<T>> getChildren() {
return this.children;
}
}
I know how to traverse a Binary Tree, but traversing a N-Ary seems much more tricky.
How would I go about traversing through this tree. I want a counter whilst I traverse the tree as to number/count each node in the tree.
Then at a specific count, I can stop and return the node at that count (perhaps remove that subtree or add a subtree at that position).
The simplest way is to implement a Visitor pattern like this:
public interface Visitor<T> {
// returns true if visiting should be cancelled at this point
boolean accept(Node<T> node);
}
public class Node<T> {
...
// returns true if visiting was cancelled
public boolean visit(Visitor<T> visitor) {
if(visitor.accept(this))
return true;
for(Node<T> child : children) {
if(child.visit(visitor))
return true;
}
return false;
}
}
Now you can use it like this:
treeRoot.visit(new Visitor<Type>() {
public boolean accept(Node<Type> node) {
System.out.println("Visiting node "+node);
return false;
}
});
Or for your particular task:
class CountVisitor<T> implements Visitor<T> {
int limit;
Node<T> node;
public CountVisitor(int limit) {
this.limit = limit;
}
public boolean accept(Node<T> node) {
if(--limit == 0) {
this.node = node;
return true;
}
return false;
}
public Node<T> getNode() {
return node;
}
}
CountVisitor<T> visitor = new CountVisitor<>(10);
if(treeRoot.visit(visitor)) {
System.out.println("Node#10 is "+visitor.getNode());
} else {
System.out.println("Tree has less than 10 nodes");
}
I am trying to create tree linked list in java and print Tree by levels of balls in metric spaces and I am unsuccessful.
create class ball:
public class Ball {
private double Point;
private double Radius;
public Ball(double Point, double Radius) {
this.Point = Point;
this.Radius = Radius;
}
public double getPoint() {
return Point;
}
public double getRadius() {
return Radius;
}
public void setPoint(double p)
{
this.Point=p;
}
public void setRadius(double r)
{
this.Radius=r;
}
public String toString(Ball b)
{
return b.Point+ " " + b.Radius;
}
}
and create class TreeNode
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class TreeNode<T> {
T data;
TreeNode<T> parent;
LinkedList<TreeNode<T>> children;
TreeNode next;
public TreeNode(T data ) {
this.data = data;
this.children = new LinkedList<TreeNode<T>>();
this.parent = null;
}
public TreeNode(T data , TreeNode<T> parent)
{
this.data=data;
this.parent=parent;
this.children = new LinkedList<TreeNode<T>>();
}
public TreeNode<T> addChild(T child)
{
TreeNode<T> childNode = new TreeNode<T>(child);
childNode.parent = this;
this.children.add(childNode);
return childNode;
}
public void setNext(TreeNode e)
{
this.next=e;
}
public TreeNode getNext()
{
return this.next;
}
public TreeNode <T> Insert(TreeNode<T> pos, T x)
{
TreeNode <T> tmp = new TreeNode <T>(x);
if(pos == null)
{
tmp.setNext(this.parent);
this.parent= tmp;
}
else{
tmp.setNext(pos.getNext());
}
return tmp;
}
public TreeNode<T> getParent() {
return parent;
}
public T getData() {
return data;
}
public LinkedList<TreeNode<T>> getChild ()
{
return children;
}
public void setData(T data1)
{
this.data=data1;
}
public void setParent(TreeNode<T> getParent)
{
this.parent=parent;
}
public String toString()
{
return this.data.toString() ;
}
}
In addition create class cover tree levels
my problem is insert element to tree
public class CoverTreeLevels {
static final int LEVELS = 25;
public static Data d;
public static void Insert(TreeNode node, TreeNode newNode)
{
newNode.parent=node.parent;
node.parent=newNode.parent;
}
public static void buildTree(double [][] data)
{
double rootRadius =d.Find_Max_Radiues(d.data);
Ball rootBall = new Ball(data[0][0], rootRadius);
TreeNode root = new TreeNode<Ball>(rootBall);
TreeNode last = root;
for (double i = 1, lastRadius = rootRadius / 2; i < LEVELS - 1; i++, lastRadius /= 2) {
Ball ball = new Ball( data[0][0] , lastRadius);
last = last.addChild(ball);
for (int j = 1; j < data.length; j++) {
TreeNode<Ball> n = last;
while (true)
{
if(d.dist(j, 0)> lastRadius)
{
Ball newBall = new Ball(data[j][0], lastRadius);
n.addChild(newBall) ;
}
n.getParent();
}
}
}
}
and class Data which includes data in metric spaces.
Am I headed in the right direction?
For one, it looks like you have some issues with access modifiers in this code.
Here, you're referencing private properties of these objects without using the getters/setters you specified. This will be a compiler error.
Second, your insert method seems to be setting the node.parent to itself.
public static void Insert(TreeNode node, TreeNode newNode)
{
newNode.parent=node.parent; // new node's parent is being set to current node's parent.
node.parent=newNode.parent; // current node's parent being set to newNode's parent, which you just assigned to node.parent above
}
To insert properly, you'd need to insert the newNode itself into the equation:
public static void Insert(TreeNode node, TreeNode newNode)
{
if ( node != null && newNode != null) {
TreeNode temp;
temp = node.getParent(); // get the current node's parent
node.setParent(newNode); // set the new parent of current node to newNode
newNode.setParent(temp); // set the new node's parent to current node's old parent
}
}
Now you should have a properly functioning insert.