How to Define N-nary Tree in Java?


In order to define a N-ary tree, we need to be able to store the Node value and its children – which is a list of the Node. And the Node type can be referenced recursively. See below Java Class Node:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Node {
    public Node(int val, Node[] children) {
        this.val = val;
        this.children = children;
    }
    
    public int getVal() {
        return this.val;
    }
    
    public Node[] getChildren() {
        return this.children;
    }
    
    private int val;
    private Node[] children;
}
class Node {
    public Node(int val, Node[] children) {
        this.val = val;
        this.children = children;
    }
    
    public int getVal() {
        return this.val;
    }
    
    public Node[] getChildren() {
        return this.children;
    }
    
    private int val;
    private Node[] children;
}

Then, we can create nodes first, and build a N-nary tree by linking them.

1
2
3
4
Node A = new Node(1, null);
Node B = new Node(2, null);
Node C = new Node(3, null);
Node root = new Node(0, new Node[]{A, B, C});
Node A = new Node(1, null);
Node B = new Node(2, null);
Node C = new Node(3, null);
Node root = new Node(0, new Node[]{A, B, C});

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
184 words
Last Post: Teaching Kids Programming - Find Root of N-Ary Tree using Hash Set
Next Post: Simple Blockchain Example in Java

The Permanent URL is: How to Define N-nary Tree in Java?

Leave a Reply