7

What does the statement 'arraylist<treenode> children; ' mean and do? Can...

 2 years ago
source link: https://www.codeproject.com/Questions/5322716/What-does-the-statement-arraylist-treenode-childre
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

I am a beginner in java and learning Data Structures and algorithms and I am currently learning trees. However, I cannot understand how a tree has been implemented using ArrayLists. I cannot understand the meaning of:

Copy Code
ArrayList<TreeNode> children;


Also, could the person who answers check whether the comments give the correct explanation of each step?

The code is given below:
Copy Code
import java.util.*;//Imported package

public class TreeNode{//Created class TreeNode for nodes of trees that contain two fields data(the data to be stored in each node) and children (as every node except root node has a child)//

  String data;//Data tobe stored is of type string
  ArrayList<TreeNode> children;//What does this mean and do?

  public TreeNode(String data){//Constructor for TreeNode class
    this.data=data;
    this.children=new ArrayList<TreeNode>();
  }

  public void addChild(TreeNode node){//Method to add child
    this.children.add(node);
  } 

  public String print(int level){//Print tree according to the level
    String ret;
    ret=" ".repeat(level)+data+"\n";
    for(TreeNode node:this.children){
      ret +=node.print(level+1);
    }
    return ret;
  }
}


What I have tried:

I have searched the internet however there are no proper explanations on trees using ArrayLists. My code is from the Udemy course.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK