0
votes

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;
}
1
Read books on tree insertion (e.g Sedgewick Algorithms in Java) , without studying these technics, it is unlikely that you correctly reinvent the wheelAlexWien

1 Answers

0
votes

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;
    } 
}