Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

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
...