How to implement a tree data-structure in Java

1 Answer

0 votes
import java.util.List;
import java.util.ArrayList;

public class Node {
    private int value;
    private List<Node> children;

    public Node(int value) {
        this.value = value;
        this.children = new ArrayList<>();
    }
    
    public void addChild(Node child) {
        children.add(child);
    }
    
    public int getValue() {
        return value;
    }
    
    public List<Node> getChildren() {
        return children;
    }
    
    public void printTree(Node node) {
        System.out.println(node.getValue());
        
        for (Node child : node.getChildren()) {
            printTree(child);
        }
    }
    
    public static void main(String args[]) {
        Node root = new Node(1);
        
        root.addChild(new Node(5));
        root.addChild(new Node(9));
        root.addChild(new Node(7));
        root.addChild(new Node(2));
        root.addChild(new Node(4));
        
        root.printTree(root);
    }
}
  
  
  
  
/*
run:
     
1
5
9
7
2
4
     
*/

 



answered Nov 13, 2023 by avibootz
...