Reputation: 191
I am implementing a tree class from scratch, I have data fields and constructor like below: public class TreeNode implements Node{ int data; TreeNode child; TreeNode parent; String name; Boolean visited;
public TreeNode(int data){
this.data = data;
child = null;
parent = null;
name = null;
visited = false;
}
one of the method I need to implement is getChildren(Node n), which returns a list that contains all children of Node n. I have no idea about how to find all children of nodes. thank you for your help!
public List<Node> getChildren() {
List<Node> children = new ArrayList<>();
while(!children.contains(this.child)){
children.add(this.child);}
return children;
}
Upvotes: 0
Views: 457
Reputation: 128
You should declare your ArrayList outside of the class declaration so that you may use it in all of your methods. You would then need some way to add a new child node to your current node, which addChild(Treenode child)
takes care of.
public class TreeNode {
private ArrayList<TreeNode> children;
public TreeNode(int data){
children = new ArrayList<>();
}
public void addChild(TreeNode child){
children.add(child);
}
public ArrayList<TreeNode> getChildren(){
return children;
}
}
Upvotes: 0